單向數(shù)據(jù)流中props的兩種應用場景
- 單向數(shù)據(jù)流:通過 props 傳遞數(shù)據(jù)是單向的,也就是父組件數(shù)據(jù)變化時會傳遞給子組件,但是反過來不行。
- 單向數(shù)據(jù)流的目的:是盡可能的將父子組件解耦,避子組件無意中修改了父組件的狀態(tài)。
- 單向數(shù)據(jù)流的應用場景:業(yè)務中會經(jīng)常遇到兩種需要改變 prop 的情況
第一種:
父組件傳遞初始值進來,子組件將它作為初始值保存起來,在自己的作用域下可以隨意使用和修改。這種情況可以在組件 data 內(nèi)再聲明一個數(shù)據(jù),引用父組件的 prop。
步驟一:注冊一個組件
步驟二:將父組件的數(shù)據(jù)傳遞進來,并在子組件中使用 props 接收
步驟三:將傳遞進來的數(shù)據(jù)通過初始值保存起來。
Vue.component('my-component', {
props: ['msg'],
template: '<div>{{count}}</div>',
data() {
return {
count: this.msg //步驟三:將傳遞進來的數(shù)據(jù)通過初始值保存起來。
}
}
})
第二種:
prop 作為需要被轉變的原始值傳入,這種情況使用計算屬性就可以了
步驟一:注冊組件
步驟二:將父組件的數(shù)據(jù)傳遞進來,并在子組件中用 props 接收
步驟三:將傳遞進來的數(shù)據(jù)通過計算屬性進行重新計算
//在input中輸入數(shù)字,改變div的高度為相應的大小
<input type="text" v-model="height">
<width-component :height="height"></width-component>
Vue.component('width-component', {
props: ['height'],
template: '<div :style="style"></div>',
data() {
return {
}
},
computed: {
style() {
return {
height: this.height + 'px',
background: 'red',
width: '30px'
}
}
}
})