vue复习(vuex状态管理)

vue工作流

  • 通过state存储数据
  • 然后在组件展示
  • 接着通过action请求接口
  • 通过mutation更新state数据
  • 以此类推

使用

1、创建状态管理

建立文件store/index.js (建立仓库)

import Vue from 'vue'
import Vuex from 'vuex'
// 导入各个模块的小仓库
import goods from './models/goods'

Vue.use(Vuex)
export default new Vuex.Store({
  state: {
  },
  getter: {
  },
  mutations: {
  },
  actions: {
  },
  modules: {
    // 模块化 如:goods (模块名)
    goods
  }
})

建立文件store/goods/index.js (建立子仓库)

export default {
    namespaced: true,
    state: {
    goodsFenlei 
	  },
	  getter: {
	  // 类似于过滤器 对数据起到有个包装的作用
	  },
	  mutations: {
	   setGoodsFenlei(state,params) { // 函数调用 更改store中的数据
            state.goodsFenlei = params
        },
	  },
	  actions: {
	  // 通过commit 来调用 mutations 中的方法
	  // 商品分类数据列表
        getGoodsFenlei(context ,params) { // context 固定参数 params 传入的参数 可以省略不写
            //调动mutations更新数据
            getFenletByType(params)
                .then(res=>{
                    context.commit('setGoodsFenlei', res.data) 
                    // 调用mutations 中的setGoodsFenlei 方法来更改store中的数据
                })
            } 
	  }
    }

激活仓库

在main.js中

import store from './store'
new Vue({
 router,
 store,
 render: h => h(App),
}).$mount('#app')

页面中调用仓库中是数据 vue项目中 (简写)

// 按需导入
import { 
    mapActions, 
    mapState, 
    mapMutations
} from 'vuex'

...mapState({  // 用来获取仓库中数据 写在 computed 属性中 
    方法名: state => state.moduleA.状态,
    方法名: state => state.moduleB.状态
}),
...mapGetters({ // 对仓库中数据进行修饰 写在 computed 属性中
    方法名: 'moduleA/方法名',
    方法名: 'moduleB/方法名'
})
...mapActions({ // 调用方法对数据进行修改  写在 methods
    方法名: 'moduleA/方法名',
    方法名: 'moduleB/方法名',
}),
...mapMutations({  // 异步请求 对数据进行跟新 写在 method
    方法名: 'moduleA/方法名',
    方法名: 'moduleB/方法名'
})

补充 (没有简写的用法) (不推荐)

const store = new Vuex.Store({
    //存放组件状态(组件数据)
    state: {
        age: 0,
        name: 'jack'
    },
    //派生出新的状态(新的数据)
    getters: { //可以认为是 store 的计算属性
        //参数:组件数据对象
        username(state) {
            return state.name + ',hello'
        }
    },
    //更新组件状态(更新组件数据)
    mutations: {
        incrment(state) {
            //直接更新数据
            state.+= 1
        }
    },
    //更新组件状态(更新组件数据)
    actions: {
        incrmentAction(context) {
            //调动mutations更新数据
            context.commit(名称, 参数)
        }
    }
})

new Vue({
    store,//激活或注册
    computed: {
        this.$store.state.this.$store.getters.//辅助函数
        ...Vuex.mapState([1,...,键n]),
        ...Vuex.mapGetters([1,...,键n])
    },
    action: {
        this.$store.commit(名称, 参数)
        this.$store.dispatch(名称,参数)
        //辅助函数
        ...Vuex.mapMutations([1,...,键n]),
        ...Vuex.mapActions([1,...,键n])
    }
})
发布了24 篇原创文章 · 获赞 6 · 访问量 4100

猜你喜欢

转载自blog.csdn.net/qq_42714690/article/details/104567109