vue中v-model父子组件通信

有这样的需求,父组件绑定v-model,子组件输入更改父组件v-model绑定的数值。是怎么实现的呢?

实际上v-model 只是语法糖而已。

<input v-model="inputValue" />
<input v-bind:value="inputValue" v-on:input="inputValue= $event.target.value" />

实际上他们是一样的。

举个例子,父组件代码:

<template>
 <div id="demo">
  <test-model v-model="inputValue"></test-model>
  <span>{{inputValue}}</span>
</div>
</template>
<script>
    import testModel from 'src/components/testModel'
    export default {
      data(){
            return{
                 inputValue: "inputValue"
            }
        },
        components: {
            testModel,
        }
    }
</script>

<style lang="scss" scoped>
</style>

子组件代码如下:

<template>
<span>
      <input
        ref="input"
        :value="value"
        @input="$emit('ababab', $event.target.value)"
      >
    </span>
</template>
<script>

    export default {
        data(){
            return{
            }
        },
        props: ["value"],
 // 使用model, 这儿2个属性,prop属性说,我要将value作为该组件被使用时v-model能取到的值,event说,我emit ‘ababab’ 的时候,参数的值就是父组件v-model收到的值。
        model: {
            prop: 'value',
            //这个事件名可以随意写,它实际上是规定了子组件要更新父组件值需要注册的方法
            event: 'ababab'
        }
    }
</script>
<style lang="scss" scoped>
</style>

以上,就实现了子组件修改父组件v-model绑定的值。

 // 使用model, 这儿2个属性,prop属性说,我要将msg作为该组件被使用时(此处为aa组件被父组件调用)v-model能取到的值,event说,我emit ‘cc’ 的时候,参数的值就是父组件v-model收到的值。

它的原理是

1.展示:父组件v-model,子组件接收一个props值value,将它展示到子组件自己的input上。

2.改变:当子组件自身发生改变时,触发自身的input方法,然后触发父组件的事件方法,改变父组件的value,进而改变接收的props,实现自身展示的改变

posted @ 2020-04-02 11:26  apple78  阅读(306)  评论(0)    收藏  举报