本文摘自PHP中文网,作者coldplay.xixi,侵删。
一、关于vue中watch的认识
我们要监听一个属性的的变化就使用watch一般是父组件传递给子组件的时候
?1、常见的使用场景
1
2
3
4
5
6
7
8
...
watch:{
value(val) {
console.log(val);
this
.visible = val;
}
}
...
相关学习推荐:javascript视频教程
?2、如果要一开始就执行
1
2
3
4
5
6
7
8
9
10
...
watch: {
firstName: {
handler(newName, oldName) {
this
.fullName = newName +
'-'
+
this
.lastName;
},
immediate:
true
,
}
}
...
?3、深度监听(数组、对象)
1
2
3
4
5
6
7
8
9
10
...
watch: {
obj: {
handler(newName, oldName) {
console.log(
'///'
)
},
immediate:
true
,
deep:
true
,
}
...
二、关于子组件修改父组件属性认识
在vue2.0+ 后不再是双向绑定,如果要进行双向绑定需要特殊处理。
[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "你修改的属性名"
?1、通过事件发送给父组件来修改
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
**在子组件test1中**
<input type=
"text"
v-model=
"book"
/>
<button @click=
"add"
>添加</button>
<p v-
for
=
"(item, index) of books"
:key=
"index"
>{{item}}</p>
...
methods: {
add() {
this
.$emit(
'update'
,
this
.book);
this
.book =
''
;
},
},
**在父组件中**
<test1 :books=
"books"
@update=
"addBook"
></test1>
...
addBook(val) {
this
.books =
new
Array(val)
},
?2、使用.sync 来让子组件修改父组件的值(其实是上面方法的精简版)
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
30
**在父组件中,直接在需要传递的属性后面加上.sync**
<test4 :word.sync=
"word"
/>
**在子组件中**
<template>
<p>
<h3>{{word}}</h3>
<input type=
"text"
v-model=
"str"
/>
</p>
</template>
<script>
export
default
{
props: {
word: {
type: String,
default
:
''
,
},
},
data() {
return
{
str:
''
,
}
},
watch: {
str(newVal, oldVal) {
this
.$emit(
'update:word'
, newVal);
}
}
}
</script>
?3、在子组件中拷贝一份副本
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
30
31
32
33
34
35
**子组件中**
export
default
{
props: {
checkModalGroup: {
type: Array,
default
: [],
required:
false
,
}
},
data() {
return
{
copyCheckModalGroup:
this
.checkModalGroup,
}
},
methods: {
checkAllGroupChange(data) {
this
.$emit(
'updata'
, data);
},
},
watch: {
checkModalGroup(newVal, oldVal) {
this
.copyCheckModalGroup = newVal;
}
}
}
**父组件中直接更新传递给子组件的数据就可以**
...
roleCheckUpdata(data) {
this
.roleGroup = data;
},
...
相关学习推荐:编程视频
以上就是vue中让子组件修改父组件数据的方法 的详细内容,更多文章请关注木庄网络博客 !
相关阅读 >>
vue 3.2发布啦,站起来继续学!
vue 配什么ui框架比较好
vue +webpack2实现路由懒加载的方法介绍
vue 中怎么导出excel文件?
在vue style中使用data中的变量的方法详解
vue weex是啥?
vue mixins是什么
vue .js算开发工具吗
vue 通常在项目中干什么
浅析vue 创建组件的几种方式
更多相关阅读请进入《vue 》频道 >>
¥83.86元 人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » vue中让子组件修改父组件数据的方法