【发布时间】:2021-11-04 03:32:30
【问题描述】:
我正在尝试在我的父组件(创建用户表单)和子组件(可重复使用的选择框)之间创建双向绑定。
父组件
<template>
<Selectbox :selectedOption="selectedRole" :options="roles" />
<span>SelectedRole: {{ selectedRole }}</span>
</template>
<script>
import Selectbox from '@/components/formElements/Selectbox.vue';
export default {
components: {
Selectbox,
},
async created() {
await this.$store.dispatch('roles/fetchRoles');
this.selectedRole = this.roles[0].value;
},
data() {
return {
selectedRole: null,
};
},
computed: {
roles() {
return this.$store.getters['roles/roles'].map((role) => ({
value: role.id.toString(),
label: role.name,
}));
},
},
};
</script>
我将角色作为选项传递,将 selectedRole 变量作为 selectedOption 传递。
子组件
<template>
<select :value="selectedOption" @input="(event) => $emit('update:selectedOption', event.target.value)">
<option v-for="option in options" :value="option.value" :key="option.value">{{ option.label }}</option>
</select>
</template>
<script>
export default {
props: {
options: {
type: Array,
required: true,
},
selectedOption: {
type: String,
required: false,
},
},
};
</script>
selectedOption 被一起赋值给该值。选择另一个值时,我想在父组件中更新传递的下降值。因此,我正在使用 $emit 函数,但现在无法正常工作。
我也尝试过使用v-model来组合value和change属性但是没有成功。
<select v-model="selectedOption">
正确的方法是什么?
代码:Codesandbox
【问题讨论】:
标签: vue.js