当前位置:首页>开发>正文

vue组件中props有什么作用

2023-04-29 02:41:11 互联网 未知 开发

 vue组件中props有什么作用

vue组件中props有什么作用

1. 在组件内的data对象中创建一个props属性的副本

因为result不可写,所以需要在data中创建一个副本myResult变量,初始值为props属性result的值,同时在组件内所有需要调用props的地方调用这个data对象myResult。
Vue.component("switchbtn", {
template: "{{myResult?开:关}}
",
props: ["result"],
data: function () {
return {
myResult: this.result//data中新增字段
}
},
......
})

2. 创建针对props属性的watch来同步组件外对props的修改
此时在组件外(父组件)修改了组件的props,会同步到组件内对应的props上,但是不会同步到你刚刚在data对象中创建的那个副本上,所以需要再创建一个针对props属性result的watch(监听),当props修改后对应data中的副本myResult也要同步数据。
Vue.component("switchbtn", {
template: "{{myResult?开:关}}
",
props: ["result"],
data: function () {
return {
myResult: this.result
}
},
watch: {
result(val) {
this.myResult = val//新增result的watch,监听变更并同步到myResult上
}
},

最新文章