你别忘了有vuex

195 阅读2分钟

1:vuex是什么?

vuex其实就是用来统一管理vue组件状态的工具

2:为什么你应该学习vuex?

当你项目越来越大,组件越来越多,传参的方法对于多层嵌套的组件将会非常繁琐,并且对于兄弟组件间的状态传递无能为力。通过父子组件直接引用或者通过事件触发去修改状态等通常会增加维护的难度。

3:怎么用?让我们开始吧!
创建vuex实例,暴露出去
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
    
})
挂载在你需要使用的vue实例中(vuex依赖vue)
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from '上面暴露文件的地址'
Vue.config.productionTip = false

new Vue({
  router,
  store,  //挂载在你需要的vue实例中就可以正式可是使用了
  render: h => h(App)
}).$mount('#app')

别害怕vuex中的state,actions,getters,mutations
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

//store其实你可以理解为一个仓库
export default new Vuex.Store({
    //state装里仓库的物品
    state:{
        //比如鸡蛋有一个
        egg: 1
    },
    //action:其实最终的目标也是为了修改仓库中的物品,比如上面的鸡蛋,
    只不过这里一般包含一些复杂业务逻辑,比如异步获取数据,等
    actions:{
        //这里说明一下,actions,mutations都是为了修改state中的数据,有什么区别呢?
        actions中的方法,可以传入一个content,content中就可以读取到mutations的方法,
        从而提交给mutations去修改数据,而mutations则可以直接修改state
        newEgg(content){
            content.commit('add',1)
        }
    },
    //getters,可以理解为vue中的计算属性,一般用于对state仓库中的修饰,过滤的计算操作,
    既然说他像计算属性,那一定不要忘记了return
    getters:{
      getEggValue(state){
          return state.egg
      }
    },
    //mutations,就是放一些方法,目的也去为了去处理state中的数据
    mutations:{
        add(state,n = 1){
            state.egg= state.egg + n
        },
        reduce(state,n = 1){
              state.egg= state.egg - n

        }
    }

})
vue中组件中去使用它吧
<template>
    <div>
        <div>{{egg}}</div>
        <div>getter : {{getEggValue}}</div>
        <div>
            <button @click="go">增加</button>
        </div>
        <div>
            <button @click="back">减少</button>
        </div>
        <div>
            <button @click="fromAction">action</button>
        </div>
    </div>
</template>

<script>
    //使用了那个属性方法就要引入它,这个很重要
    import {mapState,mapMutations,mapActions,mapGetters} from 'vuex'
    export default {
        name: "baseVuex",
        computed:{
            //在计算属性中利用解构拿到vuex仓库中state,getters下的值
            ...mapState(['egg']),
            ...mapGetters(['getEggValue'])
        },
        methods:{
            //在methods中利用解构拿到vuex仓库中Actions,Mutations下的方法
            ...mapMutations(['add','reduce']),
            ...mapActions(['newEgg']),
            go(){
                this.add();
            },
            back(){
                this.reduce();
            },
            fromAction(){
              this.newEgg()
            }
        }
    }
</script>

<style scoped>

</style>


下一篇谈谈vuex中的命名空间