• .sync 修饰符:进行父子组件间相互传递数据


    2.3.0+ 新增

    在有些情况下,我们可能需要对一个 prop 进行“双向绑定”。不幸的是,真正的双向绑定会带来维护上的问题,因为子组件可以修改父组件,且在父组件和子组件都没有明显的改动来源。

    这也是为什么我们推荐以 update:myPropName 的模式触发事件取而代之。举个例子,在一个包含 title prop 的假设的组件中,我们可以用以下方法表达对其赋新值的意图:

    this.$emit('update:title', newTitle)

    然后父组件可以监听那个事件并根据需要更新一个本地的数据属性。例如:

    <text-document
    
      v-bind:title="doc.title"
    
      v-on:update:title="doc.title = $event"
    
    ></text-document>

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

    <text-document v-bind:title.sync="doc.title"></text-document>


    示例:

    在父组件index.vue下引入子组件childrenOne为例,使用.sync属性,会在mounted生命周期里面打印出childrenOne,而不是index。

    <template>
        <div class="content">
                <childrenOne :title.sync="doc.title"></childrenOne>
            </div>
        </div>
    </template>
    <script type="text/javascript">
        import childrenOne from '../../components/childrenOne.vue'
        export default{
            data () {
                return {
                    doc:{
                        title:'parents'
                    },
                }
            },
            mounted (){
           //childrenOne
                console.log('test', this.doc.title);
            },
            components : {
                childrenOne
            }
        }
    </script>
    在子组件childrenOne.vue的生命周期mounted里面通过
    this.$emit('update:title', this.newTitle);
    设置title属值
    <template>
        <div class="content">
            {{ title }}
        </div>
    </template>
    <script type="text/javascript">
        export default{
            props:{
                title: ''
            },
            data () {
                return {
                    newTitle:'childrenOne'
                }
            },
            mounted (){
                this.$emit('update:title', this.newTitle);
            },
        }
    </script>
  • 相关阅读:
    vim tab 和4个空格
    python 入门
    pyenv 以及 virtualenv
    Redis Cluster 理论知识
    使用Redis SETNX 命令实现分布式锁
    go runtime scheduler
    LeetCode Valid Parentheses
    LeetCode Rotate Image
    leetcode
    HDU 3657 Game(取数 最小割)经典
  • 原文地址:https://www.cnblogs.com/tanweiwei/p/10607413.html
Copyright © 2020-2023  润新知