我正在尝试在父组件(创建用户表单)和子组件(可重用选择框)之间创建双向绑定。
父组件
<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>
Run Code Online (Sandbox Code Playgroud)
我将角色作为选项传递,并将 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>
Run Code Online (Sandbox Code Playgroud)
selectedOption 一起分配给值。当选择另一个值时,我想更新父组件中传递的值。因此我正在使用一个$emit函数,但现在不起作用。
我也尝试使用 v-model 来组合值并更改属性,但没有成功。
<select v-model="selectedOption">
Run Code Online (Sandbox Code Playgroud)
正确的方法是什么?
代码:Codesandbox
我想这就是您想要实现的处理:https://codesandbox.io/s/practical-orla-i8n3t ?file=/src/components/Selectbox.vue
如果在子组件上使用v-model,则要在子组件中妥善处理。
<custom-select v-model="value" />
<!-- IS THE SAME AS -->
<custom-select
:modelValue="value"
@update:modelValue="value = $event"
/>
Run Code Online (Sandbox Code Playgroud)
因此,如果您使用v-model,具有该名称的属性modelValue将被传递到子组件。如果发生modelValue更改(这意味着选择列表中的另一个选项被选中),您必须发出一个更改事件,表明已modelValue更改:$emit('update:modelValue')。v-model如果发生此事件,则会自动更新其值。
资料来源:https ://learnvue.co/2021/01/everything-you-need-to-know-about-vue-v-model/
| 归档时间: |
|
| 查看次数: |
1646 次 |
| 最近记录: |