学无先后,达者为师

网站首页 Vue 正文

vue2 自定义事件 v-model .sync

作者:苏Sue酥 更新时间: 2022-04-22 Vue

将原生事件绑定到组件

vue-将原生事件绑定到组件

	<div id="app">
        <base-input v-on:focus="onFocus" v-model="message" label="姓名">base-input>
    div>
    <script>
        Vue.component('base-input', {
            inheritAttrs: false,
            props: ['label', 'value'],
            computed: {
                inputListeners: function () {
                    var vm = this
                    // `Object.assign` 将所有的对象合并为一个新对象
                    return Object.assign({},
                        // 我们从父级添加所有的监听器
                        this.$listeners,
                        // 然后我们添加自定义监听器,
                        // 或覆写一些监听器的行为
                        {
                            // 这里确保组件配合 `v-model` 的工作
                            input: function (event) {
                                vm.$emit('input', event.target.value)
                            }
                        }
                    )
                }
            },
            template: `
                
            `,
            
        })
        new Vue({
            el: '#app',
            data() {
                return {
                    message: 'sss'
                }
            },
            methods: {
                onFocus(val) {
                    console.log(val)
                }
            },
        })  
    script>

.sync 修饰符

.sync 修饰符

prop—父子传值

	<div id="app">
        <father />
    div>
	Vue.component('father', {
            template: `
                
切换
`
, components: { son: { template: `
隐藏
`
, methods: { fn() { this.$emit('isShow', false) } } } }, data() { return { show: true } }, methods: { isShow(val) { console.log(val); this.show = !this.show } }, })

使用 .sync

	// 
	//  // 当子触发this.$emit('update:isChange', false),这里的show = this.$emit('update:isChange', false) 传的 false
        Vue.component('father', {
            template: `
                
切换
`
, components: { son: { props: ['isChange'], template: `
隐藏
`
, methods: { fn() { this.$emit('update:isChange', false) } }, watch: { isChange(val) { console.log(val); } } } }, data() { return { show: true } }, methods: { isShow(val) { console.log(val); this.show = !this.show } } }) new Vue({ el: '#app', data() { return { message: 'sss' } }, })

注意:.sync官方给出的解释就是一种语法糖的意思
最后:sync只是给大家伙提供了一种与父组件沟通的思路而已!如果只是单纯的在子组件当中修改父组件的某个数据时,建议使用sync,简单,快捷,不需要在传一个自定义方法来接收了

原文链接:https://blog.csdn.net/ME_GIRL/article/details/124254419

栏目分类
最近更新