基於如下狀況javascript
//父組件 data:{ //對象形式 } //子組件 data:function(){ return { //函數形式 } }
例子以下java
<div id="app"> //父組件 <p>{{total}}</p> <mime @increment1="incrementTotal" ref="child" :num-a="total" num-s="total"></mime> <button type="button" @click="clickref">調用子組件</button> </div> //子組件 <template id="myInput"> <button @click="add">{{counter}}</button> </template> <script> new Vue({ el:'#app', data :{ total: 0 }, methods:{ incrementTotal : function(){ }, clickref:function(){ } }, components:{ 'mime' :{ template:'#myInput', data : function(){ return{ counter : 0 } }, props:['numA','numS'], methods:{ add : function(){ } } } } }); </script>
子組件調用父組件app
{{total}} <mime @increment="incrementTotal"></mime> <template id="myInput"> <button @click="add">{{counter}}</button> </template> ... <script> .... data:{ tatal: 0 }, methods:{ incrementTotal:function(){ this.total +=1; } }, components:{ data : function(){ return:{ counter : 0 } }, methods : { add : function(){ this.counter +=1; this.$emit('increment'); //子組件經過 $emit觸發父組件的方法 increment 還能夠傳參 this.$emit('increment' ,this.counter); } } } </script>
父組件調用子組件函數
<mime ref="child"></mime> <button type="button" @click="clickref">調用子組件</button> <template id="myInput"> <button @click="add">{{counter}}</button> </template> ... <script> .... methods:{ clickref:function(){ var child = this.$refs.child; //獲取子組件實例 child.counter = 45; //改變子組件數據 child.add(11); //調用子組件方法 add } }, components:{ data : function(){ return:{ counter : 0 } }, methods : { add : function(num){ this.counter +=1; console.log('接受父組件的值:',num) //num爲11 } } } </script>
組件間互調this
//新建一個空的 var bus = new Vue() // 觸發組件 A 中的事件 bus.$emit('id-selected', 1) // 在組件 B 建立的鉤子中監聽事件 bus.$on('id-selected', function (id) { // ... })
總結: 太繁瑣,直接用Vuexcode