您的位置:首页 > Web前端 > Vue.js

vuex 基本用法、兄弟组件通信,参数传递

2017-04-20 13:15 543 查看

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)
})

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: