# vuex-brand **Repository Path**: duans/vuex-brand ## Basic Information - **Project Name**: vuex-brand - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2020-08-12 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # vuex使用介绍 ## 学习目标 - 什么是vuex - vuex的组成部分 - vuex使用步骤 ## 什么是vuex? > Vuex 是一个专为 Vue.js 应用程序开发的**状态管理模式**。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。Vuex 也集成到 Vue 的官方调试工具 [devtools extension](https://github.com/vuejs/vue-devtools),提供了诸如零配置的 time-travel 调试、状态快照导入导出等高级调试功能。 !![](https://vuex.vuejs.org/vuex.png) ## vuex使用步骤 - 下载vuex: `npm i vuex -S` - 创建store实例, 实现数据管理 - `store.js` ```js import Vue from 'vue'; import Vuex from 'vuex'; // 创建store实例对象之前, 必须把vuex注册成vue的插件 Vue.use(Vuex); const store=new Vuex.Store({ state:{ comments:[] }, mutations:{ // 删除评论 delComment (state,id) { state.comments=state.comments.filter(item=>item.id!=id) }, // 新增评论 addComment(state,comment){ state.comments.unshift(comment); }, // 获取默认评论列表 getComments(state,comments){ state.comments=comments } }, actions:{ // 异步获取默认的评论列表 // getInitComments({dispatch, commit, getters})=>commit('getComments',comments); getInitComments(context){ const comments=[{ id: 1, content: "人生若只如初见, 又何须伤感别离", author: "duans", posttime: new Date("2019/03/08").toLocaleDateString() }, { id: 2, content: "若一切都已云烟成雨, 我能否变成淤泥,再一次沾染你?", author: "duans", posttime: new Date().toLocaleDateString() }] // 通过延时定时器模拟异步请求 setTimeout(() => { context.commit('getComments',comments); }, 2000); } }, getters:{ // 计算评论数量 commentsCount:state=>{ return state.comments.length } } }); export default store ``` - 启用modules模块 ```js import Vue from 'vue'; import Vuex from 'vuex'; // 创建store实例对象之前, 必须把vuex注册成vue的插件 Vue.use(Vuex); const store = new Vuex.Store({ modules: { // 评论模块 comments: { // 启用单独的命名空间(默认注册在全局命名空间) namespaced: true, state: { comments: [] }, mutations: { // 删除评论 delComment(state, id) { state.comments = state.comments.filter(item => item.id != id) }, // 新增评论 addComment(state, comment) { state.comments.unshift(comment); }, // 获取默认评论列表 getComments(state, comments) { state.comments = comments } }, actions: { // 异步获取默认的评论列表 getInitComments({ commit }) { const comments = [{ id: 1, content: "人生若只如初见, 又何须伤感别离", author: "duans", posttime: new Date("2019/03/08").toLocaleDateString() }, { id: 2, content: "若一切都已云烟成雨, 我能否变成淤泥,再一次沾染你?", author: "duans", posttime: new Date().toLocaleDateString() }] // 通过演示定时器模拟异步请求 setTimeout(() => { commit('getComments', comments); }, 2000); } }, getters: { // 计算评论数量 commentsCount: state => { return state.comments.length } } } } }); export default store ``` - 将`store`实例挂载到`vue`实例对象上(这样在vue组件中就可以通过`this.$store`来调用`store`对象操作数据) - `main.js` ```js // main.js import Vue from 'vue' import App from './App' // 导入vuex实例对象store import store from './store' Vue.config.productionTip = false new Vue({ el: '#app', components: { App }, template: '', store }) ``` ## State ### 在组件中调用 ```js this.$store.state.comments // 如果使用了modules模块, 并且启用了单独的namespace命名空间 this.$store.state.moduleName.comments ``` ### 使用`mapState`分发`state` ```js import { mapState } from "vuex"; export default { computed:{ // 将comments映射成this.$store.state.comments ...mapState(['comments']) // 如果使用了modules模块, 并且启用了单独的namespace命名空间 ...mapState('moduleName',['comments']) } } ``` ## Getter ### 在组件中调用 ```js this.$store.getters.commentsCount // 如果使用了modules模块, 并且启用了单独的namespace命名空间 this.$store.getters['moduleName/commentsCount'] ``` ### 使用`mapGetters`分发`getters` ```js import { mapGetters } from "vuex"; export default { computed:{ // 将commentsCount映射成this.$store.getters.commentsCount ...mapGetters(['commentsCount']) // 如果使用了modules模块, 并且启用了单独的namespace命名空间 ...mapGetters('moduleName',['commentsCount']) } } ``` ## Mutation - `mutations`中的方法只能是**同步方法** > 更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数: > 你不能直接调用一个 mutation handler。这个选项更像是事件注册:“当触发一个类型为 increment 的 mutation 时,调用此函数。”要唤醒一个 mutation handler,你需要以相应的 type 调用 store.commit 方法: ### 在组件中调用 ```js const comment={ id:1, author:'zs', content:'张三的歌', posttime:new Date() } // 通过commit方法触发addComment() this.$store.commit('addComment',comment) // mutations的另外一中提交方式 this.$store.commit({type: 'addComment',comment}) // 如果使用了modules模块, 并且启用了单独的namespace命名空间 this.$store.commit('ModuleName/addComment',comment) ``` ### 使用`mapMutations`分发`mutations` ```js import { mapMutations } from "vuex"; export default { methods:{ // 将this.addComment()映射成this.$store.commit('addComment') // 将this.delComment()映射成this.$store.commit('delComment') ...mapMutations(['addComment','delComment']) // 如果使用了modules模块, 并且启用了单独的namespace命名空间 ...mapMutations('moduleName',['addComment','delComment']) } } ``` ## Actions > Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。当我们在之后介绍到 Modules 时,你就知道 context 对象为什么不是 store 实例本身了。 - Action 类似于 mutation,不同在于: - Action 提交的是 mutation,而不是直接变更状态。 - Action 可以包含任意**异步操作**。 ### 在组件中调用 ```js this.$store.dispatch('getInitComments') // 如果使用了modules模块, 并且启用了单独的namespace命名空间 this.$store.dispatch('ModuleName/getInitComments') ``` ### 使用`mapActions`分发`actions` ```js import { mapActions } from "vuex"; export default { methods:{ // 将this.getInitComments()映射成this.$store.dispatch('getInitComments') ...mapActions(['getInitComments']) // 如果使用了modules模块, 并且启用了单独的namespace命名空间 ...mapActions('moduleName',['getInitComments']) }, created(){ // 通过异步请求,获取默认数据 this.getInitComments() } } ``` ## Module > 由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。 为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割: ```js const moduleA = { state: { ... }, mutations: { ... }, actions: { ... }, getters: { ... } } const moduleB = { state: { ... }, mutations: { ... }, actions: { ... } } const store = new Vuex.Store({ modules: { a: moduleA, b: moduleB } }) store.state.a // -> moduleA 的状态 store.state.b // -> moduleB 的状态 ``` # 参考文档 [Vuex官方文档](https://vuex.vuejs.org/zh/) [品牌管理案例数据接口文档](http://106.13.182.88:3001/)