选择后在模板内显示文本(使用文本字段和值字段)



我正在使用BootstrapVue.

我有一个b-form-select,我在孩子.vue的选择中显示我的name(=文本字段),并将我的age(=值字段)emit给我的parent.vue。这很好用。

现在我也想show我的name,所以我child.vue template中的文本字段- 我怎样才能实现?

现在,我正在使用watch来检测选择某些内容时的变化并emitvalue..但是在这里我还想检查我的text-field并将其"打印"在我的b-form-select下方。

我的模板(儿童.vue)

<b-form-select v-model="selected_Person" :options="persons" text-field="name" value-field="age"></b-form-select>
<div> {{ Here I want to see the name of my Person }} </div>

我的脚本(child.vue)

data() {
return {
persons: [
{"name": "Hagrid", "age": "81"},
{"name": "Harry", "age": "18"},
{"name": "Ron", "age": "19"},
{"name": "Snape", "age": "48"}
],
selected_Person: null,
}
},
watch: {
selected_Person() {
this.$emit('selected_Person', this.selected_Person) //Here I emit my age, because it's my value
}

方法1:交换text-field值和value-field

<b-form-select v-model="selected_Person" :options="persons" text-field="age" value-field="name"></b-form-select>
<div> {{ selected_Person }} </div>

方法-2:

您可以使用computed属性,例如

<b-form-select v-model="selected_Person" :options="persons" text-field="name" value-field="age"></b-form-select>
<div> {{ getPersonName }} </div>

data() {
return {
persons: [
{"name": "Hagrid", "age": "81"},
{"name": "Harry", "age": "18"},
{"name": "Ron", "age": "19"},
{"name": "Snape", "age": "48"}
]
}
},
computed: {
getPersonName() {
return this.persons.filter(person => person.age == this.selected_person)[0].name; // logic is applicable only when you set value-field to `age`
// In case if there are multiple persons with the same age then use the below code
// return this.persons.filter(person => person.age == this.selected_Person).map(per => per.name).join(',');
}
},
watch: {
selected_Person() {
this.$emit('selected_Person', this.selected_Person) //Here I emit my age, because it's my value
}

如何将 v-model 绑定到观察者?我认为观察者用于监视data()属性中的特定值。您应该在 data() 中定义一个 'selected_Person' 属性并观察该值,因此您可以在template中显示如下: -

data() {
return {
persons: [
{"name": "Hagrid", "age": "81"},
{"name": "Harry", "age": "18"},
{"name": "Ron", "age": "19"},
{"name": "Snape", "age": "48"}
],
selected_Person: null
}
},
watch: {
selected_Person() {
this.$emit('selected_Person', this.selected_Person) //Here I emit my age, because it's my value
}

在模板中: -

<b-form-select v-model="selected_Person" :options="persons" text-field="name" value-field="age"></b-form-select> 
<div> {{ selected_Person }} </div>

相关内容

  • 没有找到相关文章

最新更新