父組件通過屬性向子組件傳值[toc]
<div id="root">
<counter :count="6" @inc="handleIncrease"></counter>
<counter :count="1" @inc="handleIncrease"></counter>
<div>{{total}}</div>
</div>
子組件通過事件向外傳值
<script>
//定義局部組件,父組件通過屬性給子組件傳值
var counter = {
props: ['count'], //接收父組件屬性count
//子組件的data一定要是一個函數(shù)
data: function() {
return {
number: this.count
}
},
template: '<div @click="handleClick">{{number}}</div>',
//單向數(shù)據(jù)流:父組件可以通過屬性向子組件傳遞參數(shù),子組件可以使用該數(shù)據(jù)
//但是子組件不可以修改父組件傳過來的參數(shù)(因為子組件改數(shù)據(jù)會影響其它子組件)
methods: {
handleClick: function() {
this.number = this.number + 2;
//子組件通過事件向外傳值.向外出發(fā)inc(名稱自取)事件
this.$emit('inc',2); //2表示加了2
}
}
}
var vm=new Vue({
el:"#root",
components: {
counter: counter
},
data:{
total: 5
},
methods: {
handleIncrease: function(step) {
//alert(step);//步長
this.total += step;
}
}
});
</script>
組件的參數(shù)校驗和非props屬性
<div id="root">
<child content="hello world"></child>
</div>
<script>
//組件的參數(shù)校驗:父組件通過屬性向子組件傳遞參數(shù)玩郊,同時子組件也可以對父組件參數(shù)做一定的約束
Vue.component('child',{
props: {
content: {
type: String,
required: false, //約束可傳可不傳
default: 'default value', //設(shè)置屬性默認值
validator: function(value) {
//傳入的content的內(nèi)容長度大于5
return (value.length > 5)
}
}
//content: [ String, Number ], //約束傳遞的值為字符串或數(shù)字
},
template: "<div>{{content}}</div>"
})
var vm=new Vue({
el:"#root"
</script>
給組件綁定原生事件
<div id="root">
<child @click.native="handleClick"></child>
</div>
<script>
Vue.component('child',{
template: "<div>Child</div>",
})
var vm=new Vue({
el:"#root",
methods: {
handleClick: function() {
alert('click原生點擊事件')
}
}
});
</script>