场景:父组件给子组件传值list,子组件中list更新后,父组件中需要感应到list的更新
方法一:使用 .sync 修饰符(Vue 2.3.0+ 引入,Vue 3 中作为建议的替代方案)
- 只传一个值
// 父组件
<template>
<checkbox :list-arr.sync="list" />
</template>
<script>
export default {
data() {
return {
list: [],
}
}
}
</script>
// 子组件checkbox.vue
<template>
...
</template>
<script>
export default {
props: {
listArr: {
type: Array,
default: () => [],
},
},
methods: {
change(newvalue) {
// 在更新listArr后的使用$emit更新父组件的list
this.$emit('update:listArr', newvalue)
}
}
}
</script>
这样写的好处是改变了传统的子组件给父组件$emit值,父组件中还需定义一个函数接收
- 传多个值且需要同步更新的写法
// 父组件
<template>
<checkbox
:value="value"
:listArr="list"
@update:value="value= $event"
@update:list="list = $event"
/>
</template>
<script>
export default {
data() {
return {
list: [],
value: [],
}
}
}
</script>
// 子组件checkbox.vue
<template>
...
</template>
<script>
export default {
props: {
listArr: {
type: Array,
default: () => [],
},
value: {
type: Array,
default: () => [],
},
},
methods: {
change(newvalue) {
// 在更新listArr后的使用$emit更新父组件的list
this.$emit('update:listArr', newvalue)
this.$emit('update:value', newvalue)
}
}
}
</script>
方法二:使用 v-model(对于自定义组件,在 Vue 2.2.0+ 中)
// 父组件
<template>
<checkbox v-model="value" />
</template>
<script>
export default {
data() {
return {
value: [],
}
}
}
</script>
// 子组件checkbox.vue
<template>
...
</template>
<script>
export default {
model: {
prop: 'value',
event: 'change'
},
methods: {
updateValue(newvalue) {
// 在更新listArr后的使用$emit更新父组件的list
this.$emit('change', newvalue)
}
}
}
</script>
这种我没试过,先记录