vuex 学习总结

创建 单独文件 store.js

//内部引用  

import Vue from "vue"

import Vuex from "vuex"

Vue.use(Vuex)

 

模块化

const store = new Vuex.Store({
    state,
    getters,
    actions,
    mutations 
})

 

state :存放属性 如同data

const state = {
  lists : [
    {name :  "cz", age : 20 },
    {name :  "cz", age : 20 },
  ],
  count : 0   
}

 

getters :获取数据  如同计算属性

const getters = {
  cou : state => {
        return state.count
  },
list : state
=> { var listFor = state.lists.map( a => { return { name : a.name, age : a.age } return listFor } } }

 

actions : 用户行为  如同 methods 方法  里面存用户改变时候的方法

const actions = {
   //
   add({commit}){
     commit("muAdd")   //
   },

   //
   cut({commit}){
     commit("muCut")
   },

   //list
  ageAdd({commit},num){
      commit("ageAdd",num)
  }

}

 

mutations: 操作数据  在有用户行为后 操作数据改变数据

const mutations = {
  muAdd: state => {
    state.count ++
  },
  muCut : state => {
    state.count --
  },

  ageAdd : (state,num) => {
    state.lists.forEach( element => {
element.age += num
}) } }

 

 最后  把store暴露出去  expore defult store  

在main.js中引用 store   impore store from "./store.js"

 

 

在各个组件中如何调用 store内的数据

通过 this.$store 方法获取store内的数据    $store 是  vuex中的对象

在计算属性中直接return出想要的数据 如  

computed:{
  one(){
    return this.$store.state.lists
  }
},

 

或者 

 

先把 想要获取的数据通过 import { } from "vue" 导入到 当前组件 

再通过 ...mapActions(['muAdd','muCut'])

 

posted @ 2019-08-05 18:45  想上天与太阳并肩  阅读(115)  评论(0编辑  收藏  举报