Vue筆記(六)——Vue組件通訊&Vuex

組件通訊

vue自己的組件通訊

  • 父==>子:父組件向子組件傳參或者調用子組件的方法
  • 子==>父:子組件向父組件傳參或者調用父組件的方法
  • 兄弟之間:兄弟組件之間傳參或者調用方法

父子通訊

  • 傳參 - props
思路:定義子組件的屬性(自定義),父組件賦值給子組件
  • 調用方法(1) - $refs
思路:定義子組件的屬性-ref="a",父組件經過: this.$refs.a.子組件方法();
  • 調用方法(2) - children
思路:父組件經過: this.$children[0].子組件方法();

子父通訊

  • 調用方法(1) - $parent.$emit("父組件自定義事件");
思路:父組件在組件的生命週期(mounted)用$on定義事件,子組件用 this.$parent.$emit("父組件自定義事件");
  • 調用方法(2) - $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>
  • 調用方法(3) - parent
思路:父組件在調用子組件時用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,這樣來達到兄弟之間組件的通訊

Vuex - 狀態管理通訊

跨組件通訊的一種實現方式
  • 用到就封裝一個組件.js
  • 組件.js
// 設置屬性: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
}
  • 集合實例化 store.js
import Vue from 'Vue';
import Vuex from 'vuex';
// 引入組件.js
import transition from './transion.js';
// 實例化對象
const store = new Vue.Store({
    modules:{
        transition
    }
});
// 暴露對象
export default store;
  • 主入口app.js實例化vuex對象
// 引入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('事件名');
相關文章
相關標籤/搜索