I'm working with BootstrapVue
.
I have a b-form-select
where I show my name
(= text field) inside the selection in my child.vue and emit
my age
(=value field) to my parent.vue. This works well.
Now I also want to show
my name
, so my text-field in my child.vue template
- how can I achieve that?
For now I'm using watch
to detect changes when something is selected and emit
this value
.. but here I also want to check my text-field
and "print" it below my b-form-select
.
My template (child.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>
My script (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
}
CodePudding user response:
Method-1: Swapping text-field
and value-field
values
<b-form-select v-model="selected_Person" :options="persons" text-field="age" value-field="name"></b-form-select>
<div> {{ selected_Person }} </div>
Method-2:
You can use computed
property for this like
<b-form-select v-model="selected_Person" :options="persons" text-field="name" value-field="age"></b-form-select>
<div> {{ getPersonName }} </div>
and
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
}
CodePudding user response:
How are you binding v-model to a watcher?? I think the watchers are used to watch a particular value in your data()
property. You should define a 'selected_Person' property in your data() and watch that value and consequently you can display in the template
like this: -
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
}
In the template: -
<b-form-select v-model="selected_Person" :options="persons" text-field="name" value-field="age"></b-form-select>
<div> {{ selected_Person }} </div>