• 使用环境:父子组件间进行交互,在父组件上绑定事件处理函数,在子组件上触发事件($emit),并传参。
      • $emit 作用是循环执行当前实例的 _events 属性内某个 event (事件名)对应的事件回调列表。也就是触发事件。
    • 功能:子组件不直接改变 data,而是传一个值给父组件,在父组件上更新 data 的值。
    • .sync 做了什么:$emit 会将参数储存到 $event 变量上,.sync 修饰符等同与监听绑定的事件并获取 $event 变量赋值给之前给子组件传的值。
      • 代码:<Comp :foo.sync="bar"></Com"> 等同于

    <Comp :foo="bar" @update:foo="val => bar = val">

    • 示例:

      1. <div id="app">
      2. <div>{{bar}}</div>
      3. <Comp :foo.sync="bar"/>
      4. <!-- <Comp :foo="bar" @update:foo="bar = $event" /> -->
      5. </div>
      6. <script>
      7. Vue.component('Comp', {
      8. template: '<div @click="increment">点我+1</div>',
      9. data() { return {copyFoo: this.foo} },
      10. props: ['foo'],
      11. methods: {
      12. increment: function() {
      13. this.$emit('update:foo', ++this.copyFoo);
      14. }
      15. }
      16. });
      17. new Vue({
      18. el: '#app',
      19. data: {bar: 0}
      20. });
      21. </script>
    • Vue规则:

      • 组件不能修改 props 外部数据
      • this. $emit 可以触发事件,并传参
      • $event 可以获取 $emit 的参数
    • 另外,Vue 文档中提到几点需要注意的:
      • 带有 .sync 修饰符的的 v-bind 不能和表达式一起使用(例如 :money.sync=" money+'!'" 是无效的)
      • 我们用一个对象同时设置多个 prop 的时候,也可以将 .sync 修饰符和 v-bind 配合使用。但是需要注意,将 v-bind.sync 用在一个字面量的对象上是无效的,例如 v-bind.sync="{ title: doc.title }",因为在解析一个像这样的复杂表达式的时候,有很多边缘情况需要考虑。