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
組件端使用:
使用的時候后,可以直接掛載后使用,掛載后就變成了自己組件的數據或者方法了。:
掛載點: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)
}
}
},
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) })
