vue2.0 子組件props接受父組件傳遞的值,能不能修改的問題整理
父組件代碼:
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
36
37
38
39
40
41
42
43
|
<!-- -->
<
template
>
<
div
class=''>
<
el-link
type="danger">傳值為對象:</
el-link
>
<
div
>
父組件中顯示fatherData的值:{{fatherData}}
<
l0705components
:fatherData="fatherData"></
l0705components
>
</
div
>
<
br
><
br
><
br
>
<
el-link
type="danger">傳值為字符串,使用v-model傳值:</
el-link
>
<
div
>
父組件中顯示fatherData2的值:{{fatherData2}}
<
l0705components
v-model="fatherData2"></
l0705components
>
</
div
>
<
br
><
br
>
<
el-link
type="danger">傳值為字符串:</
el-link
>
<
div
>
父組件中顯示fatherData3的值:{{fatherData3}}
<
l0705components
:fatherData3="fatherData3"></
l0705components
>
</
div
>
</
div
>
</
template
>
<
script
>
import l0705components from './views/l0705components'
export default {
name: "L0705L",
components: {
l0705components
},
data() {
// 這里存放數據
return {
fatherData:{
name:"李四",
age:"14"
},
fatherData2:'父組件的數據2',
fatherData3: '父組件的數據3'
}
}
}
</
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
<!-- -->
<
template
>
<
div
class=''>
<
div
v-if="fatherData">
子組件中顯示fatherData的值:{{fatherData}}
<
el-button
type="danger" @click="changeFather">
點擊修改父組件fartherData的值-姓名改為“王五”
</
el-button
>
</
div
>
<
div
v-if="value!==''">
<
input
v-model="value">
</
div
>
<
div
v-if="fatherData3!==''">
子組件中顯示fatherData3的值:{{fatherData3}}
<
el-button
type="danger" @click="changeFather3">
點擊修改父組件fartherData3的值,改為“哈哈哈哈哈”
</
el-button
>
</
div
>
</
div
>
</
template
>
<
script
>
export default {
props:{
fatherData:{
type:Object
},
value: {
type: String,
default: ''
},
fatherData3: {
type: String,
default: ''
}
},
name: "l0705components",
data() {
// 這里存放數據
return {
}
},
// 方法集合
methods: {
changeFather(){
this.fatherData.name = '王五'
},
changeFather3() {
this.fatherData3 = '哈哈哈哈哈'
}
}
}
</
script
>
|
頁面展示:
測試結果說明:
1.父組件傳遞一個對象,子組件接受,子組件中,直接修改接受到的對象里面的值,可以修改,父子組件的值都會隨之改變
2.使用v-model傳值,修改input里面的值,會報錯
意思就是props傳遞的值不能進行修改
3.點擊修改第三個值,在子組件中的值會修改,但是父組件中不能修改,報錯
總結:
父子組件傳值時,父組件傳遞的參數,數組和對象,子組件接受之后可以直接進行修改,並且會傳遞給父組件相應的值也會修改。
如果傳遞的值是字符串,直接修改會報錯。
不推薦子組件直接修改父組件中的參數,避免這個參數多個子組件引用,無法找到造成數據不正常的原因