所有的 prop 都使得其父子 prop 之间形成了一个单向下行绑定:父级 prop 的更新会向下流动到子组件中,但是反过来则不行。这样会防止从子组件意外改变父级组件的状态,从而导致你的应用的数据流向难以理解。
在 JavaScript 中对象和数组是通过引用传入的,所以对于一个数组或对象类型的 prop 来说,在子组件中改变这个对象或数组本身将会影响到父组件的状态。可以通过这种方式双向随意的改变数据,下面代码示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>单向数据流</title>
<script src="js/vue.js"></script>
</head>
<body>
<div id="test">
<favue></favue>
</div>
<template id="fa">
<div>
<p>父组件:{{user.name}}{{user.address}}</p>
<input type="button" value="改变数据" @click='change'>
<childvue :user='user'></childvue>
</div>
</template>
<template id="child">
<div>
<p>子组件</p>
<p>子组件接收到的数据: {{user.name}}{{user.address}}</p>
<input type="button" value="改变数据" @click='change'>
</div>
</template>
<script >
new Vue({
el:'#test',
components:{
'favue':{
template:'#fa',
data() {
return {
user:{
name:'tom',
address:'shanghai'
}
}
},
methods: {
change(){
this.user.name='父级名字'
}
},
components:{
'childvue':{
template:'#child',
props:['user'],
methods: {
change(){
this.user.name="alice";
}
},
}
}
}
}
})
</script>
</body>
</html>