.sync修饰符实现对prop的双向绑定
在有些情况下,我们可能需要对一个 prop 进行“双向绑定”。不幸的是,真正的双向绑定会带来维护上的问题,因为子组件可以修改父组件,且在父组件和子组件都没有明显的改动来源。2.3.0+ 新增.sync 修饰符,可以实现prop双向绑定。
举个例子,在一个包含visible prop的子组件中,
复制代码
1
2
3props: { fileList: '', },
可以用以下方法赋新值:
复制代码
1this.$emit('update:fileList', data)
然后父组件可以监听那个事件并根据需要更新一个本地的数据属性。例如:
复制代码
1
2
3
4<child v-bind:fileList="parentFile" v-on:update:visible="parentFile = $event" ></child>
我们为这种模式提供一个缩写,即 .sync 修饰符:
然后在父组件中:
复制代码
1<child :fileList.sync="parentFile"></child>
自定义组件v-model
v-model 只是一个语法糖,实际的含义是:
复制代码
1
2
3
4<child v-bind:value="parentValue" v-on:input="parentValue = arguments[0]"> </child>
默认情况下,一个组件的 v-model 会利用名为 value 的prop和 名为input事件,但是诸如单选框、复选框之类的 输入类型可能把 value 属性用作了别的目的。model 选项可以用来避免这样的冲突:
需要定制 v-model :
父组件写法如下,
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22<template> <div> {{list}} <child v-model="list"> </child> </div> </template> <script> import child from './child'; export default { name: 'parent', components: { child }, data() { return { list: [] }; } } </script>
子组件写法:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29<template> <div> <el-button type="text" @click="remove" >删除</el-button> </div> </template> <script> export default { model: { prop: 'list', event: 'change' }, props: { list: { type: Array, default() { return []; } }, }, methods: { remove() { this.$emit('change', newList); } } } </script>
最后
以上就是冷酷铃铛最近收集整理的关于prop双向绑定的全部内容,更多相关prop双向绑定内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复