美文网首页
Vue 中的 sync 修饰符

Vue 中的 sync 修饰符

作者: 雪映月圆 | 来源:发表于2019-03-19 11:11 被阅读0次

子组件修改父组件中的某个属性值,正常写法

<body>
    <div id="app">
        <child :msg="msg" @change="doChange"></child>
    </div>

    <script src="./js/vue.js"></script>
    <script>

        // 子组件的配置对象
        const child = {
        template: `
                <div>
                    <h1>{{msg}}</h1>
                    <button @click="change">点击修改h1的内容</button>
                </div>
            `,
        props: {
            msg: String
        },
        methods: {
            change: function() {
            this.$emit("change", "这是被子组件修改后的内容");
            }
        }
        };

        // 注册子组件
        Vue.component("child", child);

        const vm = new Vue({
        el: "#app",
        data: {
            msg: "这是父组件中的数据"
        },
        methods: {
            doChange: function(data) {
            this.msg = data;
            }
        }
        });
    </script>
</body>

使用sync修饰符的写法

操作步骤:

  1. 子组件中: this.$emit("update:msg", params); //此处触发的事件名称必须是 "update:变量名"
  2. 在父组件的组件模板中,找到对应的子组件标签,把其中的 :msg="msg" 改写为 :msg.sync="msg"
  3. 注意: 此处的 "update:msg
<body>
    <div id="app">
        <child :msg.sync="msg"></child>
    </div>

    <script src="./js/vue.js"></script>
    <script>

        // 子组件的配置对象
        const child = {
        template: `
                <div>
                    <h1>{{msg}}</h1>
                    <button @click="change">点击修改h1的内容</button>
                </div>
            `,
        props: {
            msg: String
        },
        methods: {
            change: function() {
            this.$emit("update:msg", "这是被子组件修改后的内容");
            }
        }
        };

        // 注册子组件
        Vue.component("child", child);

        const vm = new Vue({
        el: "#app",
        data: {
            msg: "这是父组件中的数据"
        }
        });
    </script>
</body>

相关文章

  • 深入理解vue 修饰符sync【 vue sync修饰符示例】

    在说vue 修饰符sync前,我们先看下官方文档:vue .sync 修饰符,里面说vue .sync 修饰符以前...

  • 2018-10-11

    vue 修饰符sync【 vue sync修饰符示例】 先看下一个参考的文章:深入理解vue 修饰符sync【 v...

  • 关于vue的一些实践

    参考文章:vue中需要注意的问题总结(上) 1.对于sync的使用 参考vue的修饰符sync 在有些情况下,我们...

  • vue3 的 v-model

    子组件 类似于vue2的.sync 修饰符

  • .sync修饰符及MVVM

    .sync修饰符 父组件 子组件 vue的数据响应式

  • vue中的.sync修饰符

    产生缘由 vue中组件间的传值为单向传递,子组件想要更新父组件的值,需要用emit触发父组件函数,用.sync修饰...

  • Vue 中的 .sync 修饰符

    原理.sync修饰符本质上是语法糖,将代码进行了简化。核心原理是对子组件, 对父组件的pros进行监听并且更新。先...

  • Vue 中的 sync 修饰符

    子组件修改父组件中的某个属性值,正常写法 使用sync修饰符的写法 操作步骤:子组件中: this.$emit("...

  • vue中的.sync修饰符

    .sync是一个语法糖 Vue的三个规则 组件不能修改props外部数据 $emit可以触发事件并传参 $even...

  • Vue中的.sync修饰符

    在有些情况下,我们可能需要对一个 prop 进行“双向绑定”。不幸的是,真正的双向绑定会带来维护上的问题,因为子组...

网友评论

      本文标题:Vue 中的 sync 修饰符

      本文链接:https://www.haomeiwen.com/subject/uhqgmqtx.html