vuex的使用流程

1.引入一个安装好的vuex
2.注册vuex
3.实例化
4.定义核心
state 数据
mutation 方法
actions 异步方法
getters 对已有数据加工形成新数据,store中数据变化,getter中的数据也会变化
5.挂载store到vue
6.在需要的组件中使用vuex

import Vue from 'vue'
import Vuex, {
    
     Store } from 'vuex'
Vue.use(Vuex)
export default new Store({
    
    
  state: {
    
    
    count: 1,
    cart: JSON.parse(localStorage.getItem('cart') || '[]')
  },
  mutations: {
    
    
    addCart (state, goodsinfo) {
    
    
      let flag = false
      state.cart.some(item => {
    
    
        if (item.id === goodsinfo.id) {
    
    
          item.count += goodsinfo.count
          flag = true
        }
      })
      if (!flag) {
    
    
        state.cart.push(goodsinfo)
      }
      localStorage.setItem('cart', JSON.stringify(state.cart))
    }
  },
  actions: {
    
    
    addCart2 ({
    
     commit }, goodsinfo) {
    
    
      commit('addCart', goodsinfo)
    }
  },
  getters: {
    
    
    getAllCount (state) {
    
    
      let c = 0
      state.cart.some(item => {
    
    
        c += item.count
      })
      return c
    },
    getAllPrice (state) {
    
    
      let allPrice = 0
      state.cart.some(item => {
    
    
        if (item.selected === true) {
    
    
          allPrice += item.count * item.sell_price
        }
      })
      return allPrice * 100
    }
  }
})

访问核心状态
1.state

this.$store.state.count
import {
    
    mapState} from 'vuex'

computed:
{
    
    ...mapState(['count'])}

2.mutation

this.$store.commit("addCart ")
import {
    
    mapMutations} from 'vuex'

methods:
{
    
    ...mapMutations(['addCart '])}

3.actions

this.$store.dispatch("addCart2")
import {
    
    mapActions} from 'vuex'

methods:
{
    
    ...mapActions(['addCart2'])}

4.getter

this.$store.getters.名字
import {
    
    mapGetters} from 'vuex'

computed:
{
    
    ...mapGetters(['getAllCount'])}

猜你喜欢

转载自blog.csdn.net/qq_45785424/article/details/107473416