vuex的数据交互

methods:{
...mapMutations({aaa:hs}) //将mutations的方法暴露出来,进行调用 aaa是他的名字

...mapActions(['hs']) //将actions的方法暴露出来,进行调用 
hss(){
 this.$store.commit('hs') //通过某个方法让它 提交
}

hss2(){
 this.$store.dispatch('hs') //通过某个方法让它 提交 actions里
}
}

mounted(){
  this.$store.commit('hs') //可以在这里去调取数据 
  this.$store.dispatch('hs') //通过某个方法让它 提交 actions里
}

computed:{
...mapGetters(['hs']) //将Getters返回的方法内的数据暴露出来,进行调用
...mapState(['count']) //将State的数据暴露出来,进行调用
}

 computed: mapState({
        //使用箭头函数
        count: state => state.count,
        //传入字符串 ‘count’ 等同于 `state => state.count`
        count1: 'count',
        // 为了能够使用 `this` 获取局部状态,必须使用常规函数
        count2(state) {
            return state.count + this.id
        }
    })

getters: {
  // ...
  getTodoById: (state) => (id) => {
    return state.todos.find(todo => todo.id === id)
  }
}
getters: {
    doneTodos: state => {
      return state.todos.filter(todo => todo.done)
    }
  }

store.commit('increment', {
  amount: 10
}) //将数据提交到 mutations里面并且 传了一个参数payload.amount

 actions: {
    increment (context) {
      context.commit('increment')
    }
}
actions: {
  increment ({ commit }) {
    commit('increment')
  }
}

actions: {
  actionA ({ commit }) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        commit('someMutation')
        resolve()
      }, 1000)
    })
  }
}
现在你可以这样做:

store.dispatch('actionA').then(() => {
  // 将actionA 提交到 actions里 并且 将actionA 返回的Promise对象接收并输出
}) 

actions: {
//被提交到actionB 将actionA 提交到 actions里 并且 将actionA 返回的Promise对象接收并输出
  actionB ({ dispatch, commit }) {
    return dispatch('actionA').then(() => {
      commit('someOtherMutation')
    })
  }
}

猜你喜欢

转载自www.cnblogs.com/l8l8/p/9185166.html