vuex

一、文件配置vue

  在src文件夹下建立一个store文件夹,而后在store文件夹下建立一个index.js文件vuex

  index.js问价配置函数

  import  Vue  from  'vue'this

  import  Vuex  from  'vuex'spa

  Vue.use( Vuex )get

  export  default  new  Vuex.Store({it

    state:{  // 数据,组件中使用$store.state.num就能够获取到num的值io

      num:100,import

      a:10   cli

    },

    getters:{  // 至关于组件的计算属性,组件中使用$store.getters.count就能够获取到返回值了

      count(state){

        return  state.num + 100

      },

      total(state){

        return state.a * 5

      }

    },

    mutations:{  // 改变state的值,组件中使用$store.commit('ADD')调用ADD方法

      ADD(state,data){  // data为actions中ADD传的参数

        state.num ++

      },

      DEL(state){

        state.num --

      }

    },

    actions:{  // 管理或提交mutations,组件中使用$store.dispatch('DEL')

      ADD({commit,state},data){  // data是传的参数     this.$store.dispatch('ADD',num)

        commit('ADD')

      },

      DEL(context){  // context至关于$store

        context.commit('DEL')

      }

    }

  })

 

辅助函数在组件中应用

  {{count}}  {{total}}

  <div  @click="ADD">增长</div>

  import  { mapGetters,mapActions }  from  'vuex'

  methods:{

    ...mapActions(['ADD','DEL'])

  },

  computed:{

    ...mapGetters(['count','total'])

  } 

相关文章
相关标签/搜索
本站公众号
   欢迎关注本站公众号,获取更多信息