单向数据流
通过 props 传递数据是单向的,父组件数据变化会传递给子组件,而反过来不行。
目的:尽可能将父子组件解稿,避免子组件无意中修改了父组件的状态。
应用场景:
① 父组件传递初始值,子组件将初始值保存起来,在自己的作用域下可以随意使用和修改。这种情况可以在组件的 data 种声明一个数据,引用父组件传递过来的 props。
步骤:
- 注册组件
- 将父组件的数据传递进来给子组件 props 接收
- 将传递进来的数据通过初始值保存起来(通过
this.
直接获取)
<div id="app">
<child-component msg="我是父组件传递的数据"></child-component>
</div>
<script>
var app = new Vue({
el: '#app',
data: {},
components: {
'child-component': {
props: ['msg'],
template: '<div>{{childMsg}}</div>',
data: function() {
return {
// 通过 this.msg 获取初始值并保存到本地的 childMsg
childMsg = this.msg
}
}
}
}
})
</script>
② prop 作为需要被转变的原始值传入,此时用计算属性就可以了。
步骤:
- 注册组件
- 将父组件的数据传递进来给子组件 props 接收
- 将传递进来的数据通过计算属性重新计算
// 通过 input 中输入的数据直接改变 div 的宽度
<div id="app">
<input type="text" v-model="width">
<child-component :width="width" init="请输入宽度"></child-component>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
width: ''
},
components: {
'child-component': {
props: ['init', 'width'],
template: '<div :style="style">{{init}}</div>',
computed: {
style: function() {
return {
width: this.width + 'px',
background: 'red'
}
}
}
}
}
})
</script>