关于vue.js:Vue父子组件的数据通信双向绑定

Vue父子组件通信,形式有三种:
形式一:

子组件

<template>
  <div>
    <div>儿子:{{msg}}</div>
    <button @click="childBtn">儿子</button>
  </div>
</template>

<script>
export default {
  name: 'Child',
  props: {
    msg: {
      require: true,
      type: String,
      default () {
        return ''
      }
    }
  },
  model: {
    prop: 'msg',
    event: 'changeMsg'
  },
  methods: {
    childBtn () {
      if (this.msg === 'father') {
        this.$emit('changeMsg', 'mother')
      } else {
        this.$emit('changeMsg', 'father')
      }
    }
  }
}
</script>

父组件

<template>
  <div>
    <child :msg="msg" @changeMsg="changeMsg"></child>
    <div>父亲:{{msg}}</div>
    <button @click="fatherBtn">父亲</button>
  </div>
</template>

<script>
import Child from '@/components/Child'
export default {
  name: 'Index',
  components: {
    Child
  },
  data () {
    return {
      msg: ''
    }
  },
  methods: {
    changeMsg (e) {
      this.msg = e
    },
    fatherBtn () {
      if (this.msg === 'father') {
        this.msg = 'mother'
      } else {
        this.msg = 'father'
      }
    }
  }
}
</script>

父组件通过prop批改子组件的数据状态,子组件通过$emit发送事件(event)信号,告诉父组件批改父组件内的数据状态,同时父组件须要监听相干的event。

形式二:
应用v-model进行双向绑定,v-model是一种语法糖

<child v-model="msg"></child>

等价于

<child :value="msg" @input="changeMsg"></child>

然而,如果咱们须要指定子组件的prop,和监听的event应该怎么做呢?
只须要在子组件中指定model即可

model: {
  prop: 'msg',
  event: 'changeMsg'
}

残缺子组件代码如下:

<template>
  <div>
    <div>儿子:{{msg}}</div>
    <button @click="childBtn">儿子</button>
  </div>
</template>

<script>
export default {
  name: 'Child',
  props: {
    msg: {
      require: true,
      type: String,
      default () {
        return ''
      }
    }
  },
  model: {
    prop: 'msg',
    event: 'changeMsg'
  },
  methods: {
    childBtn () {
      if (this.msg === 'father') {
        this.$emit('changeMsg', 'mother')
      } else {
        this.$emit('changeMsg', 'father')
      }
    }
  }
}
</script>

形式三:
应用 .sync ,也是一种语法糖

<child :msg.sync="msg"></child>

等价于

<child :msg="msg" @update:msg="changeMsg"></child>

子组件只须要 emit(‘update:msg’)即可。
残缺子组件代码如下:

<template>
  <div>
    <div>儿子:{{msg}}</div>
    <button @click="childBtn">儿子</button>
  </div>
</template>

<script>
export default {
  name: 'Child',
  props: {
    msg: {
      require: true,
      type: String,
      default () {
        return ''
      }
    }
  },
  methods: {
    childBtn () {
      if (this.msg === 'father') {
        this.$emit('update:msg', 'mother')
      } else {
        this.$emit('update:msg', 'father')
      }
    }
  }
}
</script>

思考,形式二v-model与形式三sync有什么区别呢?
1、v-model只能指定一个属性,而sync能够应用在任意多个属性上。
2、v-model更多的是应用在示意该组件特有的“value”的变动,sync针对组件各种各样状态的传递。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理