美文网首页vueJs使用
VUE自定义组件中用.sync修饰符与v-model的区别

VUE自定义组件中用.sync修饰符与v-model的区别

作者: 记录学习生活 | 来源:发表于2020-05-09 10:20 被阅读0次

1、.sync修饰组件

<div class="container" style="margin-top: 12px;">
    <div id="demo" class="row">
        {{ say }}
        <br />
        <my-input :value.sync="say"></my-input>
    </div>
</div>


<script>
    new Vue({
        el: '#demo',
        data: {
            say: "123"
        },
        components: {
            "my-input": {
                props: ['value'],
                template: "<div><input v-bind:value='value' v-on:input='change1' />{{value}}</div>",
                watch: {
                    value: function(newValue, oldValue) {
                        alert('子组件value新旧值' + newValue + '/' + oldValue);
                        //this.$emit('update:value', newValue)
                    }

                },
                methods: {
                    change1: function(e) {
                        var v = e.target.value
                        this.$emit('update:value', v)
                    },

                }
            }
        },
        watch: {
            say: function(n, o) {
                alert('父组件新旧值' + n + '-' + o)
            }
        },
        methods: {

        }
    })
</script>

2、v-model修饰组件

<div class="container" style="margin-top: 12px;">
    <div id="demo" class="row">
        {{ say }}
        <br />
        <my-input v-model="say"></my-input>
    </div>
</div>


<script>
    new Vue({
        el: '#demo',
        data: {
            say: "123"
        },
        components: {
            "my-input": {
                props: ['value'],
                template: "<div><input v-bind:value='value' v-on:input='change' />{{value}}</div>",
                watch: {
                    value: function(newValue, oldValue) {
                        alert('子组件value新旧值' + newValue + '/' + oldValue);
                        //this.$emit('update:value', newValue)
                    }

                },
                methods: {
                    change: function(e) {
                        this.$emit('input', e.target.value)
                    }
                }
            }
        }
    })
</script>

引用链接地址:进入

相关文章

网友评论

    本文标题:VUE自定义组件中用.sync修饰符与v-model的区别

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