前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >10分钟学会vuex

10分钟学会vuex

原创
作者头像
Qiang
修改2019-06-21 10:49:42
4410
修改2019-06-21 10:49:42
举报
文章被收录于专栏:前端精髓前端精髓

Vuex全局的状态统一管理,解决组件之间状态共享和数据通信的问题。

第一步

store.js

代码语言:txt
复制
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex) // 使用插件
// 导出store实例
export default new Vuex.Store({
  state: {

  },
  mutations: {

  },
  actions: {

  }
})

第二步

main.js

代码语言:txt
复制
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

Vue.config.productionTip = false

new Vue({
  router,
  store, // 增加store属性,值是导出store的实例
  render: h => h(App)
}).$mount('#app')

通过上面两个步骤,每个组件中都有了$store属性,就是我们创建的容器。里面有commit,dispatch,state,getters,actions,mutations,在每个组件中可以通过this.$store打印出来看看。

开始使用

定义状态

代码语言:txt
复制
export default new Vuex.Store({
  state: {
	count: 1 // state中定义响应式的数据
  }
})

使用状态:在store的state中定义的状态count,在组件中可以使用this.$store.state.count获取。


定义mutations

在store的mutations中添加对应的方法

代码语言:txt
复制
export default new Vuex.Store({
  state: {
	count: 1 // state中定义响应式的数据
  },
  mutations: {
	addTen (state, num) {
		state.count = state.count + num
	}
  },
  actions: {

  }
})

提交mutations

组件中通过commit提交mutations去修改state中的状态

代码语言:txt
复制
this.$store.commit('addTen', 10)

定义actions

在store的actions中添加对应的方法

代码语言:txt
复制
export default new Vuex.Store({
  state: {
	count: 1
  },
  mutations: {
	addTen (state, num) {
		// 第一个参数是状态,第二个是传入的参数
		state.count = state.count + num
	}
  },
  actions: {
	minusTen ({commit}, num) {
		// 第一个参数是store实例,第二个是传入的参数
		setTimeout(() => {
			commit('addTen', num)
		}, 1000)
	}
  }
})

派发动作

组件中可以使用dispatch派发一个动作,来触发actions中的方法,actions可以异步的提交mutations去修改state中的状态

代码语言:txt
复制
this.$store.dispatch('minusTen', 10)

actions主要是复用,封装代码,处理异步,请求接口等等,真正修改状态放到了mutations中处理


定义getters

在store的getters中添加对应的方法

代码语言:txt
复制
export default new Vuex.Store({
  state: {
	count: 1,
	person: {
		name: '张三'
	}
  },
  getters: {
	getName (state) {
		// getters是同步的
		return state.person.name
	}
  }
})

使用getters

代码语言:txt
复制
this.$store.getters.getName

getters定义的方法相当于计算属性,相当于定义在computed一样,有缓存,依赖改变会重新计算。

组件代码演示

代码语言:txt
复制
<template>
  <div class="hello">
    <h1>{{ this.$store.state.count }}</h1>
    <h1>{{ this.$store.getters.getName }}</h1>
    <button @click="syncAdd">同步加10</button>
    <button @click="asyncAdd">异步加10</button>
  </div>
</template>

<script>
export default {
  methods: {
    syncAdd () {
      this.$store.commit('addTen', 10)
    },
    asyncAdd () {
      this.$store.dispatch('minusTen', 10)
    }
  }
}
</script>

简写

上面的写法都是在this.$store中获取属性或方法进行操作。

代码语言:txt
复制
this.$store.state.count
this.$store.getters.getName
this.$store.commit('addTen', 10)
this.$store.dispatch('minusTen', 10)

但是这些操作写起来比较繁琐,每次都要写this.$store,为了简写,所以vuex提供了一些映射的方法,直接导入到组件中就可以使用了。

代码语言:txt
复制
<template>
  <div class="hello">
    <h1>{{ count }}</h1>
    <h1>{{ getName }}</h1>
    <button @click="syncAdd">同步加10</button>
    <button @click="asyncAdd">异步加10</button>
  </div>
</template>

<script>
import {mapActions, mapState, mapMutations, mapGetters} from 'vuex'
export default {
  computed: {
    ...mapState(['count']),
    ...mapGetters(['getName'])
  },
  methods: {
    syncAdd () {
      this.addTen(10)
    },
    asyncAdd () {
      this.minusTen(10)
    },
    ...mapActions(['minusTen']),
    ...mapMutations(['addTen'])
  }
}
</script>

有一点需要说明的是,使用扩展运算符,表示这些方法返回的都是对象,mapStatemapGetters需要定义在计算属性中,因为他们定义的数据是响应式的。而mapActionsmapMutations需要定义在methods中。

拆分模块

状态是可以分层的,当一个项目维护的状态太多,可以拆分成单独的模块,在定义store中有个modules属性,里面可以定义单独的模块。

代码语言:txt
复制
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  modules: {
    'page1': {
      namespaced: true,
      state: {
        count: 1,
        person: {
          name: '张三'
        }
      },
      mutations: {
        addTen (state, num) {
          state.count = state.count + num
        }
      },
      actions: {
        minusTen ({commit}) {
          setTimeout(() => {
            commit('addTen', 10)
          }, 1000)
        }
      },
      getters: {
        getName (state) {
          return state.person.name
        }
      }
    }
  }
})

在组件中这样用

代码语言:txt
复制
<template>
  <div class="hello">
    <h1>{{ count }}</h1>
    <h1>{{ getName }}</h1>
    <button @click="syncAdd">同步加10</button>
    <button @click="asyncAdd">异步加10</button>
  </div>
</template>

<script>
import {mapActions, mapState, mapMutations, mapGetters} from 'vuex'
export default {
  computed: {
    ...mapState('page1', ['count']),
    ...mapGetters('page1', ['getName'])
  },
  methods: {
    syncAdd () {
      this.addTen(10)
    },
    asyncAdd () {
      this.minusTen(10)
    },
    ...mapActions('page1', ['minusTen']),
    ...mapMutations('page1', ['addTen'])
  }
}
</script>

每个方法都传了两个参数,第一个参数指定命名空间,第二个参数是对应的属性,为了进一步简写,可以通过帮助函数指定命名空间,指定当前组件在使用的模块。

代码语言:txt
复制
<template>
  <div class="hello">
    <h1>{{ count }}</h1>
    <h1>{{ getName }}</h1>
    <button @click="syncAdd">同步加10</button>
    <button @click="asyncAdd">异步加10</button>
  </div>
</template>

<script>
import { createNamespacedHelpers } from 'vuex'
// 创建帮助函数指定命令空间
let { mapActions, mapState, mapMutations, mapGetters } = createNamespacedHelpers('page1')

export default {
  computed: {
    ...mapState(['count']),
    ...mapGetters(['getName'])
  },
  methods: {
    syncAdd () {
      this.addTen(10)
    },
    asyncAdd () {
      this.minusTen(10)
    },
    ...mapActions(['minusTen']),
    ...mapMutations(['addTen'])
  }
}
</script>

不使用简写

代码语言:javascript
复制
this.$store.getters['page1/getName']
this.$store.state.page1.count
this.$store.commit('page1/addTen', 10)
this.$store.dispatch('page1/minusTen', 10)

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 第一步
  • 第二步
  • 开始使用
  • 简写
  • 拆分模块
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档