美文网首页
Vuex的使用

Vuex的使用

作者: 南蓝NL | 来源:发表于2019-04-30 17:34 被阅读0次
State

访问方式: 通过属性访问和辅助函数

  • 通过属性访问: this.$store.state
  • 辅助函数: ..mapState

定义

const state = {
  products,
  amount
}

使用

this.$store.state.products,
this.$store.state.amount
//  ...mapState
...mapState({ products: state => state.products })  // 等价于 ...mapState({ products: 'products' })
// 当映射的计算属性的名称与 state 的子节点名称相同,我们可以传入一个数组
...mapState(['products','amount'])   
Getter(可以认为是store的计算属性)

访问方式: 通过属性访问和辅助函数

  • 通过属性访问: this.$store.getters
  • 辅助函数: ..mapGetters(只是将store中的getter映射到局部计算属性)
    定义
// store.js
 state: {
    todos: [
      {id: 1,text:"today is come over",done: true},
      {id: 2, text: "tomorrow is comming",done: false}
    ],
   count: 10
  },
  getters:{
    doneTodos: state=>{
        state.todos = state.todos.filter(todo => todo.done)
        return state.todos;
    },
    doneTodoCount: (state) =>{
      return state.todos.length
    }
  }

此外,getters可以接受两个参数

  getters:{
    doneTodos: (state,getters )=>{
        state.todos = state.todos.filter(todo => todo.done)
        return state.todos;
    },
    doneTodoCount: (state,getters) =>{
      return getters.doneTodos
    }
  }

使用

// 组件
 computed: {
    ...mapGetters({
      "done":"doneTodos", 
      "doneTodo":"doneTodoCount"
      })
  },
  created() {
    console.log(this.done);
  },

当然咯可以带参数

// 定义
getters:{
    doneTodos: (state)=>(id)=>{
      return state.todos.filter(todo => todo.id === id).map(item =>  item.text)
    }
// 使用
this.$store.getters.doneTodos(1)
// 如果使用的是...mapGetters
...mapGetters([
  'doneTodos'
])
// 调用的时候
doneTodos(id)
Mutation(类似事件,但是是同步事务)

访问方式: 通过属性访问和辅助函数

  • 通过属性访问: this.$store.commit()
  • 辅助函数: ..mapMutations
    定义
  mutations: {
// 这里的palyload 是一个对象 
// playload  等价于 { type: 'ADD_MUTATIONS' , amount: 10}
    [ADD_MUTATIONS](state,playload){
       state.count = state.count + playload.amount
    }
  }
    addCount(){
      this.$store.commit('ADD_MUTATIONS',{amount: 10})
    }
// ADD_MUTATIONS  是定义的一个常量

使用

...mapMutations({
 add: 'addCount'
})
// or
...mapMutations([
'addCount'
])
// ...mapMutations 也可以传参
this.add({amount: 10})  // or this.addCount({amount: 10})

Actions(类似于mutation,不同在于action 提交mutation,而且可以进行异步操作)

访问方式: 通过属性访问和辅助函数

  • 通过属性访问: this.$store.dispatch()
  • 辅助函数: ..mapActions

Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。

// store.js
actions: {
  async actionA ({ commit }) {
    commit('gotData', await getData())
  },
  async actionB ({ dispatch, commit }) {
    await dispatch('actionA') // 等待 actionA 完成
    commit('gotOtherData', await getOtherData())
  }
}
// 组件内
this.$store.dispath('actionB').then()

当然也有...mapActions

模块

Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:

相关文章

网友评论

      本文标题:Vuex的使用

      本文链接:https://www.haomeiwen.com/subject/llejwqtx.html