props數(shù)據(jù)一定是單向的
<strong>prop默認是單向綁定</strong>
當父組件的屬性變化時,將傳導(dǎo)給子組件,但是反過來不會。這是為了防止子組件無意修改了父組件的狀態(tài)。
案例驗證:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="app">
<table>
<tr>
<th colspan="3">父組件</th>
</tr>
<tr>
<td>國家</td>
<td>{{country}}</td>
<td><input type="text" v-model="country"></td>
</tr>
<tr>
<td>地區(qū)</td>
<td>{{area}}</td>
<td><input type="text" v-model="area"></td>
</tr>
</table>
<br>
<my-child :child-country="country" :child-area="area"></my-child>
</div>
<template id="child">
<table>
<tr>
<th colspan="3">子組件</th>
</tr>
<tr>
<td>國家</td>
<td>{{ childCountry }}</td>
<td><input type="text" v-model="childCountry"></td>
</tr>
<tr>
<td>地區(qū)</td>
<td>{{ childArea }}</td>
<td><input type="text" v-model="childArea"></td>
</tr>
</table>
</template>
<script src="js/vue.js"></script>
<script>
new Vue({
el: '#app',
data:{
country: '中國',
area: '亞洲'
},
components:{
'my-child': {
template: '#child',
props: [ "childCountry", "childArea"]
}
}
})
</script>
</body>
</html>
- 運行結(jié)果:
vueb5.png
- 結(jié)論
在vuejs2.0中,任何試圖在組件內(nèi)修改通過props傳入的父組件數(shù)據(jù)都被認為是anti-pattern的。