• Vue2系列 — 修饰符.sync


    .sync 修饰符以前存在于 Vue1.0 版本里,后来在2.0版本中移除了 .sync 修饰符。
    但是在 2.0 发布之后的实际应用中,发现 .sync 还是有其适用之处,比如在开发可复用的组件库时。我们需要做的只是让子组件改变父组件状态的代码更容易被区分
    从 2.3.0 起重新引入了 .sync 修饰符,但是这次它只是作为一个编译时的语法糖存在。它会被扩展为一个自动更新父组件属性的 v-on 监听器。

    1 使用情景

    需要父组件给子组件传值
    子组件通过 emit 改变该值

    2 原写法:

    v-bind 传值 money 给子组件
    并绑定事件 update:money 改变 money 值

    父组件:
    <template>
      <div class="app">
        <Child
          v-bind:money="total" 
          v-on:update:money="money = $event"
        />
      </div>
    </template>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    子组件:
    <template>
      <div class="child">
        {{ money }}
        <button @click="$emit('update:money', money - 100)">
        </button>
      </div>
    </template>
    
    <script>
    export default {
      props: ["money"],
    };
    </script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    3 为了方便起见,为这种模式提供一个缩写,即 .sync 修饰符:

    示例:https://codesandbox.io/s/white-glade-xhj86?file=/src/App.vue

    父组件:
    <template>
      <div class="app">
        <Child v-bind:money.sync="total" />
        
      div>
    template>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    4 需要注意的是

    • 带有 .sync 修饰符的 v-bind 不能和表达式一起使用 (例如 v-bind:title.sync=”doc.title +
      ‘!’” 是无效的)。取而代之的是,你只能提供你想要绑定的 property 名,类似 v-model。
    • 当我们用一个对象同时设置多个 prop 的时候,也可以将这个 .sync 修饰符和 v-bind 配合使用:
    <text-document v-bind.sync="doc">text-document>
    
    • 1

    这样会把 doc 对象中的每一个 property (如 title) 都作为一个独立的 prop 传进去,然后各自添加用于更新的 v-on 监听器。

    • 将 v-bind.sync 用在一个字面量的对象上,例如 v-bind.sync=”{ title: doc.title }”,是无法正常工作的,因为在解析一个像这样的复杂表达式的时候,有很多边缘情况需要考虑。
  • 相关阅读:
    Java SpringBoot VIII
    Jetson Nano下载C++ 版本的GPIO 并配置进qt项目
    ARFoundation系列讲解 - 89 适配华为机型
    Matlab中的功率谱分析方法与实例分析
    【六、http】go的http的客户端重定向
    Elasticsearch版本和Spring Data Elasticsearch版本对应关系
    阿里内部SpringBoot进阶宝典横空出世,实战源码齐飞
    LINQ to SQL (Group By/Having/Count/Sum/Min/Max/Avg操作符)
    ORB-SLAM2算法14之局部建图线程Local Mapping
    Vue复习笔记 (二)SPA单页面应用(优化首屏加载)
  • 原文地址:https://blog.csdn.net/weixin_52268321/article/details/134541502