【问题标题】:Vue 3 two way binding with select boxVue 3 与选择框的双向绑定
【发布时间】: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


    【解决方案1】:

    我想这是你想要实现的处理: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"
    />
    

    因此,如果您使用v-model,名称为modelValue 的属性将被传递给子组件。如果modelValue 更改(这意味着选择列表中的另一个选项被选中),您必须发出一个更改事件,表明modelValue 已更改:$emit('update:modelValue')v-model 如果发生此事件,会自动更新它的值。

    来源:https://learnvue.co/2021/01/everything-you-need-to-know-about-vue-v-model/

    【讨论】:

    • 就是这样。谢谢!供更多读者参考。可以通过将 :name 添加到 v-model 来将 modelValue 重命名为其他名称:&lt;Selectbox v-model:selectedOption="selectedRole" :options="roles" /&gt;
    • 不错,不知道
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    • 1970-01-01
    • 2012-03-11
    • 2017-11-07
    • 2017-02-06
    • 2019-06-10
    相关资源
    最近更新 更多