唯品秀前端博客

官解:每一个 Vuex 应用的核心就是 store(仓库)。“store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。Vuex 和单纯的全局对象有以下两点不同:Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够实现一些工具帮助我们更好地了解我们的应用。

首先说说同步情况下怎么去更新状态,上代码

store

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

let selectModule = {
    state: {
        title: '打印title',
        list: []
    },
    mutations: {
        changeTitle(state, payload) {
            state.title = payload.title
        },
        changeList(state, list) {
            state.list = list;
        }
    },
    actions: {
        getListAction({
            commit
        }) {
            // 发送请求
            axios.get('http://easy-mock.com/mock/594f5d4b9adc231f3569be76/list/list')
                .then((data) => {
                    commit("changeList", data.data); // 拿到数据后,提交mutations,改变状态
                })
                .catch((error) => {
                    console.log(error)
                })
        }
    }
};

// this.$store.state.title
// this.$store.state.selectModule.title

// 定义一个容器
let store = new Vuex.Store({
    state: { //初始化状态
        count: 100,
        sum: 99,
        isShow: true
    },
    getters: { //类似计算属性
        filterCount(state) {
            return state.count >= 120 ? 120 : state.count;
        },
        sumGet(state) {
            return state.sum >= 200 ? 200 : state.sum
        }
    },
    mutations: { //payload接受页面事件交互传过来的参数值
        addIncrement(state, payload) {
            state.count += payload.n;
        },
        deIncrement(state, payload) {
            state.count -= payload.de;
        },
        sumFn(state, payload) {
            state.sum += payload.add;
        }
    },
    actions: {
        addAction({
            commit,
            state,
            rootState,
            dispatch,
            getters
        }, payload) {
            console.log('state', state)
            console.log('rootState', rootState)
            setTimeout(() => {
                // 改变状态,提交mutations
                commit("addIncrement", payload)
                dispatch("textAction", {
                    test: '异步回调拿到的参数'
                })
            }, 1000)
        },
        textAction(context, options) { //接收上面dispatch提交过来的参数
            console.log(options) //相当于一个异步操作里的回调函数
        }
    },
    modules: { //modules:多个store模块集合
        selectModule
    }
})
export default store

组件js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import {
    mapState,
    mapGetters,
    mapActions,
    mapMutations
} from 'vuex'

export default {
    computed: {
        ...mapGetters({
            num2: 'filterCount', //取到计算属性里的值
            sum1: 'sumGet'
        }),
        ...mapState(['count', 'sum'])
    },
    mounted() {
        console.log(this.$store.state.selectModule.title)
    },
    methods: {
        ...mapActions({ //异步action
            addHandle: 'addAction'
        }),
        ...mapMutations({ //同步
            deHandle: 'deIncrement',
            sumFn: 'sumFn'
        })
    }
}

组件模板页面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<template>
  <div>
    <h2>简易加法计算器</h2>
    <div>
      <input type="button" value="-" @click="deHandle({de:5})" />
      <span>{{count}}</span>
      <input type="button" value="+" @click="addHandle({n:1})" />
      <p>{{num2}}</p>
      <span>点击</span>
      <button @click="sumFn({add:20})">{{sum}}</button>
      <p>我被限制了大小不超过200-----------{{sum1}}</p>
      <p>{{$store.state.count}}</p>
      <!-- 另一种获取vuex数据的方式 -->
    </div>
  </div>
</template>

首先你想改变一个状态,必须是通过(commit)向mutation提交,通过vuex自身封装好的方法,可通过mapMutations提交,异步用dispatch(mapAction),不得不说的是,即使你在异步通过mapAction去提交,最终触发的还是mutations方法,也就是说真正改变vuex数据或者说状态的只应该是mutations,其他统统是野路子。当前案例代码可前往github克隆到本地调试。

本站所有文章、图片、资源等如无特殊说明或标注,均为来自互联网或者站长原创,版权归原作者所有;仅作为个人学习、研究以及欣赏!如若本站内容侵犯了原著者的合法权益,可联系我们进行处理,邮箱:343049466@qq.com
赞(1) 打赏

上一篇:

下一篇:

相关推荐

0 条评论关于"vue.js中学习使用Vuex详解教你快速入门"

表情

最新评论

    暂无留言哦~~
谢谢你请我吃鸡腿*^_^*

支付宝扫一扫打赏

微信扫一扫打赏