思路:定義子組件的屬性(自定義),父組件賦值給子組件
思路:定義子組件的屬性-ref="a",父組件經過:
this.$refs.a.子組件方法();
思路:父組件經過:
this.$children[0].子組件方法();
$parent.$emit("父組件自定義事件");
思路:父組件在組件的生命週期(mounted)用$on定義事件,子組件用
this.$parent.$emit("父組件自定義事件");
$emit("父組件自定義事件");
思路:父組件在調用子組件時用v-on把事件傳給子組件,子組件用
this.$emit("父組件自定義事件")
調用父組件傳過來的事件
<div id="app"> <h1>父組件-{{this.text}}</h1> <!-- 子組件 --> <child v-on:parentEvent="changeText()"></child> </div> <script type="text/javascript"> var vm = new Vue({ el:"#app", data:{ text:'' }, methods:{ changeText(_text){ this.text = _text; } }, components:{ 'child':{ template:'<p><label>子組件</label><input type="text" v-on:input="change" /></p>', methods:{ change(event){ this.$emit('parentEvent',event.target.value); } } } } }); </script>
思路:父組件在調用子組件時用v-on把事件傳給子組件,子組件用
this.$parent.父組件事件
<div id="app"> <h1>父組件-{{this.text}}</h1> <child></child> </div> <script type="text/javascript"> var vm = new Vue({ el:"#app", data:{ text:'' }, methods:{ changeText(_text){ this.text = _text; } }, components:{ 'child':{ template:'<p><label>子組件</label><input type="text" v-on:input="change" /></p>', methods:{ change(event){ this.$parent.changeText(event.target.value); } } } } }); </script>
和上面介紹的父子之間通訊是同樣的,由於任何連個子組件之間都會擁有一個共同的父級組件,因此兄弟組件之間的通訊就是子1向父,而後父向子2,這樣來達到兄弟之間組件的通訊
跨組件通訊的一種實現方式
// 設置屬性:state const state = { count = 0; } // 設置方法:mutaions const mutaions = { increment(_state){ _state.count += 1; } } // 執行方法 const actions = { increment(_content){ _content.commit('increment'); } } // 暴露 export default{ state, mutaions, actions }
import Vue from 'Vue'; import Vuex from 'vuex'; // 引入組件.js import transition from './transion.js'; // 實例化對象 const store = new Vue.Store({ modules:{ transition } }); // 暴露對象 export default store;
// 引入vuex對象 import store from './vuex/store.js'; // 實例化vuex對象 new Vue({ el:"#app", router, store, render:h=>h(app) });
1.調用參數javascript
$store.state.組建名.屬性
2.調用方法vue
$store.dispatch('事件名');