问题原因

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

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

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐