自定义组件 v-model 的使用

关于自定义组件如何使用 v-model,本章直讲如何使用:

一、 $emit('input', params) 

// 父组件中
<template>
    <article>
        {{flag}}
        <button @click="flag = !flag">点击</button>
        <Child v-model="flag"></Child>
    </article>
</template>
<script>
    import Child from ‘./child'
    export default {
        data:function(){
            return{
                flag: true,
            }
        },
        components:{
            Child
        }
    }
</script>

//子组件中
<template>
    <article>
        {{value}}
        <Button @click="$emit('input',!value)">点击</Button>
    </article>
</template>
<script>
export default {
    props:{
        value: Boolean,    
    }
}
</script>

二、通过在model属性中自定义事件:

//父组件中;
<template>
    <article>
        {{flag}}
        <button @click="flag = !flag">点击</button>
        <Child v-model="flag"></Child>
    </article>
</template>
<script>
import Child from './child'
export default {
    data:function(){
        return{
            flag: true,
        }
    },
    components:{
        Child
    }
}
</script>

//子组件中:
<template>
    <article>
        {{flag}}
        <Button @click="$emit('on-visible-change', !flag)">点击</Button>
    </article>    
</template>
<script>
export default {
    props:{
        flag: Boolean,
    },
    model: {
        prop: 'flag',
        event: 'on-visible-change',
    },
}
</script>
原文地址:https://www.cnblogs.com/yuzhongyu/p/10862072.html