Vue官方文檔對單向數據流有着如下定義
官網中說,在子組件中直接操作props會發出警告。實例如下
let btn = Vue.component('button-counter', {
data: function () {
return {
count: 0
}
},
props:['msg'],
template: '<button v-on:click="count++">{{msg}}你已經點了我{{ count }}次了.</button>'
})
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
},
template:"<div><btn msg='某某同學'></btn></div>",
components:{
btn
}
})
在父組件中設置子組件的msg屬性爲’某某同學‘,然後在子組件中用props拿到值並渲染到頁面,此時頁面效果如下。
可以看到’某某同學‘被正常渲染。接下來我在子組件中的created生命週期中直接操作props看是否會報錯。
created(){
this.msg='改變!'
},
可以看到紅色報錯信息。在子組件上使用v-model雙向綁定數據實際上也是單向數據流。v-model本質上就是v-on和v-bind的語法糖。
來看雙向綁定的栗子
let v_input = Vue.component('v_input', {
data: function () {
return {
count: 0,
}
},
props:['value'],
template: ` <input :value="value" @input="$emit('input', $event.target.value)"
>`
})
var app = new Vue({
el: '#app',
data: {
com_input: '請輸入'
},
template:"<div><v_input v-model='com_input'></v_input> <div>{{com_input}}</div> </div>",
components:{
v_input,
},
})
效果圖如下
因爲v-model是v-bind和v-on的語法糖,因此v-model也可以用v-bind和v-on來實現,所以下面這種寫法也是可以的
var app = new Vue({
el: '#app',
data: {
com_input: '請輸入'
},
template:"<div><v_input v-bind:value='com_input' v-on:input='com_input=$event'></v_input> <div>{{com_input}}</div> </div>",
components:{
v_input,
},
})
這兩種寫法得到的結果是一模一樣的。v-model雙向綁定和vue的單項數據流並不衝突