我正在使用BootstrapVue
.
我有一个b-form-select
,我在孩子.vue的选择中显示我的name
(=文本字段),并将我的age
(=值字段)emit
给我的parent.vue。这很好用。
现在我也想show
我的name
,所以我child.vue template
中的文本字段- 我怎样才能实现?
现在,我正在使用watch
来检测选择某些内容时的变化并emit
此value
..但是在这里我还想检查我的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>