創建一個簡單的點擊計數的功能
<div id="app">
<counter :count="0"></counter>
<counter :count="1"></counter>
</div>
<script>
var counter = {
props: ['count'],
template: '<div @click="hdclick">{{count}}</div>',
methods: {
hdclick: function(){
this.count++
}
}
}
var app = new Vue({
el:"#app",
components:{
counter: counter
}
})
利用props接受父組件傳來的count值,但是我們不能直接修改接收到的值,這樣控制檯會報錯
var counter = {
props: ['count'],
data: function(){
return {
number: this.count
}
},
template: '<div @click="hdclick">{{number}}</div>',
methods: {
hdclick: function(){
this.number++
}
}
}
我們通過data返回一個number數據,通過創建副本,並修改,不會出現問題
<div id="app">
<counter :count="0" @inc="incClick"></counter>
<counter :count="1" @inc="incClick"></counter>
</div>
<script>
var counter = {
props: ['count'],
data: function(){
return {
number: this.count
}
},
template: '<div @click="hdclick">{{number}}</div>',
methods: {
hdclick: function(){
this.number = this.number + 2;
this.$emit('inc', 2)
}
}
}
var app = new Vue({
el:"#app",
components:{
counter: counter
},
methods:{
incClick: function(temp){
this.count += temp;
}
}
})
</script>
這裏通過$emit向父組件傳遞參數值2,父組件通過@inc監聽inc事件,接收到參數,觸發根組件的incClick方法,同時接受到參數