单个双向绑定发送事件使用$emit('input',父级监听到的值),且变量名必须用value;
多个双向绑定使用$emit('update:变量名',父级监听到的值);父组件接收时,v-model 接收单个,:变量名.sync 接收多个(vue3中使用v-model:name的写法)
demo组件
<template> <ul> <h1>子组件</h1> <li> <label>a:</label><span>{{ value }}</span> <el-button @click="$emit('input', value + 1)">子组件修改a</el-button> </li> <li> <label>b:</label><span>{{ b }}</span> <el-button @click="$emit('update:b', b + 2)">子组件修改b</el-button> </li> <li> <label>c:</label><span>{{ c }}</span> <el-button @click="$emit('update:c', c + 3)">子组件修改c</el-button> </li> </ul> </template> <script> export default { props: ['value', 'b', 'c'] }; </script>
使用demo
<template> <div> <ul> <h1>父组件</h1> <li> <label>a:</label><span>{{ a }}</span> <el-button @click="a = 0">父组件修改a</el-button> </li> <li> <label>b:</label><span>{{ b }}</span> <el-button @click="b = 0">父组件修改b</el-button> </li> <li> <label>c:</label><span>{{ c }}</span> <el-button @click="c = 0">父组件修改c</el-button> </li> </ul> <demo v-model="a" :b.sync="b" :c.sync="c"></demo> </div> </template> <script> import demo from "@/vue/components/demo"; export default { components: { demo }, data() { return { a: 1, b: 2, c: 3 } }, }; </script> <style lang="scss" scoped> div { display: flex; &>* { width: 200px; } } </style>