一种解决方案是使用 sync 修饰符以及计算的 getter 和 setter:
父组件
<template>
...
<PaymentMethod :method.sync="method" :term.sync="term"/>
...
<b-btn class="float-right" variant="primary" @click="add">
OK
</b-btn>
...
</template>
<script>
export default {
data () {
return {
method: null,
term: null
}
},
...
}
</script>
子组件
<template>
...
<b-form-select v-model="_method" :options="methodOptions" />
...
<b-form-select v-model="_term" :options="termOptions" />
...
</template>
<script>
export default {
props: ['method', 'term'],
computed: {
_method: {
get () {
return this.method
},
set (value) {
this.$emit('update:method', value)
}
},
_term: {
get () {
return this.term
},
set (value) {
this.$emit('update:term', value)
}
},
},
...
}
</script>
现在使用父组件的 add 方法,您可以访问子组件的选定 method 和 term 选项:
methods: {
add() {
// this.method is the value of _method
// this.term is the value of _term
}
}
更新
由于您已声明您需要所选术语/方法的值和文本,我建议进行以下更改:
家长
<template>
...
<PaymentMethod :methods="methods"
:terms="terms"
:method.sync="method"
:term.sync="term"/>
...
<b-btn class="float-right" variant="primary" @click="add">
OK
</b-btn>
...
</template>
<script>
export default {
data () {
return {
// define your method and term arrays in the parent component.
// pass them as props to the child component.
methods: [{...}, {...}, {...}],
terms: [{...}, {...}, {...}],
method: null,
term: null
}
},
// use computed properties to retrieve the selected method / term option.
computed: {
selectedMethod () {
return this.methods.find(method => method.value === this.method)
},
selectedTerm () {
return this.terms.find(term => term.value === this.term)
},
}
...
}
</script>
儿童
<template>
...
<b-form-select v-model="_method" :options="methods" />
...
<b-form-select v-model="_term" :options="terms" />
...
</template>
<script>
export default {
props: ['method', 'term', 'methods', 'terms'],
computed: {
_method: {
get () {
return this.method
},
set (value) {
this.$emit('update:method', value)
}
},
_term: {
get () {
return this.term
},
set (value) {
this.$emit('update:term', value)
}
},
},
...
}
</script>