vuex 基本用法、兄弟組件通信,參數傳遞


vuex主要是是做數據交互,父子組件傳值可以很容易辦到,但是兄弟組件間傳值,需要先將值傳給父組件,再傳給子組件,異常麻煩。

vuex大概思路:a=new Vue(),發射數據‘msg’:a.$emit('evt','msg'),接收數據msg:a.$on('evt',msg=>this.msg=msg) ,代碼在mounted中。

vuex使用:

store端 :

一共有4大塊,state,actions,mutations、getters

//一般單獨js文件寫數據
 
import Vue from 'vue' 
import Vuex from 'vuex'
Vue.use(Vuex)
 
export default new Vuex.Store({
state: {                //state數據跟根組件data寫法一模一樣。也是儲存數據的。
  a: 1,
  b: '33'
},
actions: {               //actions里面全是方法,與mutations區別只有這兒的方法可以使用異步操作,mutations方法使用異步,調試會混亂。
  fn({ commit, state }, n) {    //{{commit,state}}寫法是es6語法,簡寫,state是默認傳參,就是上面的state,就算寫aaa也是指向state。n為組件傳過來的參數。  
      new Promise((resolve, reject) => {        //這兒模擬延遲,不模擬寫 state.a += n;commit('add')代替
      setTimeout(() => resolve(state.a += n), 1000)
    }).then(commit('add'))      //fn執行結束后,再執行mutations 中的add(){}。必須如此,否則,組件使用時收不到數據。
  },
  msgFn({ commit, state }, msg) {
    state.b = msg
    commit('add')
  }
},
mutations: {              //此處的function是同步操作的。其他的都跟上面一樣。
  add(state,n) {}          //參數跟actions一樣。
},
getters: {              // 這個跟組件的computed差不多,接收state作為參數,不接受組件傳參數。需要return值。
  c(state) {
    state.a += 1        
    return state.a--       
  },
}
})
 

組件端使用:

使用的時候后,可以直接掛載后使用,掛載后就變成了自己組件的數據或者方法了。:

掛載點:computed:

    mapState(['a'])                             或者使用:this.$store.state   獲取state對象。
    mapGetters([ 'doneTodosCount', 'anotherGetter',])      或者使用:this.$store.getters  獲取getters對象。
掛載點:methods:
    mapMutations(['mutationName'])   

    mapActions([ 'actionName',])  

      Mutations使用:

        使用方法1:無需掛載,直接使用,可在自定義methods,watch,等等函數中使用。

             this.$store.commit('mutationName',n)    使用mutiationName函數並傳遞參數n,傳過去自動變為是第二位參數,第一位參數一定是state。

        使用方法2:需掛載

            @click='mutationName(5)', 這個5 傳過去會自動變成為給函數第二個參數,第一個參數必須是state。

      Actions使用:

        使用方法一:無需掛載,直接使用。

          this.$store.dispatch('actionA',msg).then(() => {}) 傳參上同。這兒可以用then()

        使用方法2:需掛載

          @click='actionA(msg).then(fn)'  使用actionA函數,並且傳msg參數過去。參數上同  

<template>
  <div id="app">
    <button @click='fn(4)'>state.a+4</button>  <!--使用vuex傳過來的函數fn,並且傳參4-->
    <div>
      現在state.a:{{a}}
      <br>
      現在getters.c(): {{c}}   注:c=state.a+1
      <br>
      <hr>
      <aaa ></aaa>
      <hr>
      <bbb></bbb>
    </div>
  </div>
</template>

<script>
import {mapGetters,mapActions,mapMutations,mapState} from 'vuex';    //引入輔助函數,拿去掛載后就可以用了。
const {fn,msgFn}=mapActions(['fn','msgFn'])                  //對象展開運算符...測試無法用,這兒用解構代替。        
const {a,b}=mapState(['a','b'])         //解構目的在於:掛載方式如 methods:MapActions(['xxx']),自己還想在本地寫方法,怎么辦?
const {c}=mapGetters(['c'])            //於是將外面的花括號去掉,添加到methods:{fn,msgFn,myFn}中,其中myFn為本地添加的。
export default {
  computed:{
      a,b,c
  },
  methods:{
      fn,
  },
  components:{
    aaa:{              //傳遞input輸入的msg給state.b ,調用vuex里的msgFn,將msg當做參數傳過去,msgFn的代碼就是將state.b=msg。
      template:`<div><h2>我是子組件aaa</h2><p >{{c}}</p><br>state.b=input值 :<input type="text" v-model='msg'></div>`,
      computed:mapGetters(['c']),
      data(){
        return {
          msg:''
        }
      },
      methods:{
        fn,
        msgFn,
     fn1(){
       console.log(222)
     } } },
    watch:{
      msg(){  //檢測msg的值,發生變化后觸發msgFn
      this.$store.dispatch('msgFn',this.msg).then(this.fn1)
      }
    }
    bbb:{            //兄弟組件能夠顯示state.b的值。
      template:`<div><h2>我是子組件的兄弟組件bbb</h2><br>我收到aaa的輸入數據,利用state.b顯示出來 :</bbbbr><span>{{b}}</span></div>`,
      computed:mapState(['b'])
    }
  }
}

main.js中,需要將vuex.store實例掛載到根組件中。

import Vue from 'vue'
import App from './App.vue'
import store from './store.js'

new Vue({
    store,
    el: '#app',
    render: h => h(App)
})

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM