目录
#博学谷IT学习技术支持#
建立一个新的脚手架项目, 在项目中应用vuex(过程略)
在src文件下创建一个store文件夹

在index.js:
- import Vue from 'vue'
- import Vuex from 'vuex'
-
- Vue.use(Vuex)
-
- export default new Vuex.Store({
- state: {
- },
- getters: {
- },
- mutations: {
- },
- actions: {
- },
- modules: {
- }
- })
state是放置所有公共状态的属性,如果你有一个公共状态数据 , 你只需要定义在 state对象中
定义state
如何在组件中获取count?
原始形式- 插值表达式
计算属性 - 将state属性定义在计算属性中
- // 把state中数据,定义在组件内的计算属性中
- computed: {
- count () {
- return this.$store.state.count
- }
- }
辅助函数 - mapState
mapState是辅助函数,帮助我们把store中的数据映射到 组件的计算属性中, 它属于一种方便用法
1.3. vuex基础-mutationsstate数据的修改只能通过mutations,并且mutations必须是同步更新,目的是形成数据快照
数据快照:一次mutation的执行,立刻得到一种视图状态,因为是立刻,所以必须是同步
定义mutations
- const store = new Vuex.Store({
- state: {
- count: 0
- },
- // 定义mutations
- mutations: {
-
- }
- })
格式说明
mutations是一个对象,对象中存放修改state的方法
- mutations: {
- // 方法里参数 第一个参数是当前store的state属性
- // payload 载荷 运输参数 调用mutaiions的时候 可以传递参数 传递载荷
- addCount (state, payload) {
- state.count += payload
- }
- },
如何在组件中调用mutations ?
原始形式-$store
- <button @click="addCount">+1button>
-
- <script>
- export default {
- methods: {
- // 调用方法
- addCount () {
- // 调用store中的mutations 提交给muations
- // commit('muations名称', 2)
- this.$store.commit('addCount', 10) // 直接调用mutations
- }
- }
- }
- script>
辅助函数 - mapMutations
mapMutations和mapState很像,它把位于mutations中的方法提取了出来,我们可以将它导入
- import { mapMutations } from 'vuex'
- methods: {
- ...mapMutations(['addCount'])
- }
此时,就可以直接通过this.addCount调用了
state是存放数据的,mutations是同步更新数据,actions则负责进行异步操作
定义actions
- actions: {
- // 获取异步的数据 context表示当前的store的实例 可以通过 context.state 获取状态 也可以通过context.commit 来提交mutations, 也可以 context.diapatch调用其他的action
- getAsyncCount (context) {
- setTimeout(function(){
- // 一秒钟之后 要给一个数 去修改state
- context.commit('addCount', 123)
- }, 1000)
- }
- }
原始调用 - $store
- addAsyncCount () {
- this.$store.dispatch('getAsyncCount')
- }
传参调用
- addAsyncCount () {
- this.$store.dispatch('getAsyncCount', 123)
- }
辅助函数 -mapActions
- import { mapActions } from 'vuex'
- methods: {
- ...mapActions(['getAsyncCount'])
- }
直接通过 this.方法就可以调用
除了state之外,有时我们还需要从state中派生出一些状态,这些状态是依赖state的,此时会用到getters
例如,state中定义了list,为1-10的数组
- state: {
- list: [1,2,3,4,5,6,7,8,9,10]
- }
组件中,需要显示所有大于5的数据,正常的方式,是需要list在组件中进行再一步的处理,但是getters可以帮助我们实现它
定义getters
- getters: {
- // getters函数的第一个参数是 state
- // 必须要有返回值
- filterList: state => state.list.filter(item => item > 5)
- }
使用getters
原始方式 -$store
<div>{{ $store.getters.filterList }}div>
辅助函数 - mapGetters
- computed: {
- ...mapGetters(['filterList'])
- }
<div>{{ filterList }}div>