vue自定义组件,v-model完美使用方式

vue自定义组件,v-model完美使用方式

前言

当我们自定义form组件的时候,v-mode是几乎必须的,但v-mode的正确写法应该是怎样呢?
其实只要了解vue自定义组件保留的关键变量 value 和方法 input 就简单很多了。

实现效果

我们定义了父子组件,并各自有自己的输入框,父子的输入框实现双向绑定,效果如下:
在这里插入图片描述

父组件

父组件代码如下,插入了一个自定义的子组件childComponent,并使用v-model双向绑定自身的fatherValue变量,代码比较简单,不多描述。

<template>
    <div id="app">
        <div>父组件输入框:<input type="text" v-model="fatherValue"></div>
        <childComponent v-model="fatherValue" />
    </div>
</template>

<script>
    import childComponent from './childComponent.vue'

    export default {
        name: 'app',
        data() {
            return {
                fatherValue: ""
            }
        },
        components: {
            childComponent
        }
    }
</script>

子组件

子组件代码如下,请注意代码注释的讲解:

  1. props里面需定义value(双向绑定默认的变量,可自定义),父组件通过v-model绑定的fatherValue 会传给子组件props的 value

  2. 子组件的input框添加@input事件触发returnBackFn,returnBackFn向父组件传递input事件(双向绑定默认事件,可自定义),同时传递childValue的值

  3. 添加value的watch监听,当value变化时传递最新值给childValue

通过上述3步骤操作,最终实现了自定义组件 v-model的双向绑定。

<template>
    <div>
        子组件输入框:<input type="text" v-model="childValue" @input="returnBackFn">
    </div>
</template>

<script>
    export default {
        data() {
            return {
                childValue: "",
            }
        },
        watch: {
            //监听value变化(slect控件不是必要,暂时不明)
            value(newValue, oldValue) {
                this.childValue = newValue;
            }
        },
        props: {
            //value是默认双向绑定值,必须在props里面声明
            value: String
        },
        methods: {
            returnBackFn() {
                //input是默认双向绑定事件,select控件也可以用input给父组件传递数据
                this.$emit('input', this.childValue)
            },
        },
    }
</script>

发布了43 篇原创文章 · 获赞 2 · 访问量 4581

猜你喜欢

转载自blog.csdn.net/iamlujingtao/article/details/103929372