问题原因

在这里插入图片描述
在这里插入图片描述

value是我定义的props,而vue是不允许子组件改变父组件传来的参数值的,自然不能放在v-model里了,不然就被表单乱改值。

解决方法

为了让父组件能在子组件里创建双向数据绑定,我们应该自定义一个v-model,而不是传递props

子组件

<template>
    <div style="text-align: center">
        <input v-model="value" placeholder="edit me" />
    </div>
</template>

<script>
    export default {
        name: "Child",
        props: {
            modelValue: Array,
        },
        computed: {
            value: {
                get() {
                    return this.modelValue
                },
                set(value) {
                    this.$emit('update:modelValue', value)
                }
            }
        }
    }
</script>

<style scoped>

</style>

父组件

<template>
    <Child v-model="pValue"></Child>
</template>

<script>
    import Child from "@/components/Child";
    export default {
        name: "Parent",
        components: {Child},
        data() {
            return {
                pValue: '11'
            }
        }
    }
</script>

<style scoped>

</style>
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐