浅谈父子组件通信方式

最近在封装组件,我整理了一些封装方法,感谢我司的前端团队,若是还有更好的方法,欢迎来稿,欢迎切磋。前端

1、v-model的原理

vue的v-model是一个十分强大的指令,它能够自动让input里的值自动和你设定的值进行绑定,它是如何实现的呢?vue

1.语法糖:使用v-model来进行数据双向绑定以下:this

<input v-model="ying">

2.其实是这样实现的:双向绑定

<input v-bind:value="ying" v-on:input="ying=$event.target.value">
<a-input v-bind:value="ying" v-on:input="ying=arguments[0]"></a-input>

3.其实v-model只不过是一个语法糖而已,真正的实现靠的仍是code

(1) v-bind:绑定响应式数据
(2) 触发 input 事件 并传递数据 (重点)对象

2、方法

父子组件通讯,都是单项的,不少时候须要双向通讯。方法以下:事件

  1. 父组件使用:text.sync="aa" 子组件使用$emit('update:text', 'text改变后的值')
  2. 父组件传值直接传对象,子组件收到对象后可随意改变对象的属性,但不能改变对象自己。
  3. 父组件使用: v-model,子组件使用经过监听value和暴露input事件来实现v-model
  4. 父组件使用: v-model 子组件使用model

(1)使用syncip

父组件:get

<a-input :value.sync="text" ></a-input>

子组件:input

<template>
 <div>
     <input v-model="currentValue" @input="handleModelInput">
 </div>
</template>
<script>
 export default {
  props: { 
    value: [String,Number,Date],
  },
  methods: {
       handleModelInput() {
         this.$emit("update:value", this.currentValue);
       }
  },
  watch: {
     value(newValue) {
         this.currentValue = newValue
     }
</script>

(2)使用v-model 子组件触发 input 事件 并传递数据,并对value进行监听

父组件:

<a-input v-model="text">

子组件:

<input v-model="currentValue" @input="handleModelInput">
props:{
    value:[String,Number],
}
handleModelInput() {
    this.$emit('change',this. currentValue)
}
watch: {
    value(newValue) {
        this.currentValue = newValue
    }
},

(3)使用model prop属性 even事件change

父组件:

<a-input v-model="text">

子组件:
<template>
 <div>
     <input v-model="currentValue" @input="handleModelInput">
 </div>
</template>
<script>
 export default {
  model: {  
   prop: 'value',
   event: 'change'
  },
  props: {
    value:[String,Number], 
  },
  methods: {
   handleModelInput() {
      this.$emit('change', this.currentValue)
   }
  },
watch: {
    value(newValue) {
        this.currentValue = newValue
    }
 }
</script>

码字辛苦,文章如对您有帮助,麻烦支持点赞~