VueX

安装

1.npm安装

npm install vuex --save

2.新建store文件夹,index.js

//  2.1引入vue
import Vue from "vue";
//  2.2引入vuex
import Vuex from "vuex";

//  2.3安装插件
Vue.use(Vuex);

//  2.4创建store对象
const store = new Vuex.Store({
    //保存数据
    state: {},
    //计算属性
    getters: {},
    //同步修改数据
    mutations: {},
    //异步修改数据
    actions: {},
    //模块
    modules: {}
});

//  2.5导出store
export default store;

3.挂载main.js

//  3.1 引入
import store from "./store";

// 3.2挂载app
new Vue({
    store
}).$mount("#app");

保存数据:state

const store = new Vuex.Store({
    state: {
        counter: 0,
        students: [
            {name: "swk", age: 19},
            {name: "zbj", age: 23},
        ]
    }
})

全局拿取数据

<p>{{ $store.state.counter }}</p>
<p>{{ $store.state.students }}</p>

计算属性:getters

//  要点1:默认第一个参数就是state;
//  要点2:传入第二个参数getters可以直接把他当成顶层定义的getters,可以直接通过getters.XXX拿取getters内部定义的其他变量;
//  要点3:可以就把他当作计算属性使用,当数据需要发生变化时需要使用getters,需要return
const store = new Vuex.Store({
    state: {
        //  对象
        counter: 10,
        //  数组
        students: [
            {name: "swk", age: 19},
            {name: "zbj", age: 23},
            {name: "shs", age: 20},
        ]
    },
    getters: {
        //  获取counter的平方
        powerCounter(state) {
            return state.counter * state.counter;
        },
        
        //  获取大于20岁的人信息
        moreTwentyStu(state) {
            //filter过滤
            return state.students.filter(s => {
                return s.age > 20;
            })
        },
        //  获取大于20岁的人的个数
        moreTwentyStuLength(state, getters) {
            //  传入第二个参数getters可以直接拿取别的地方的getters,使用方法:getters.XXX;
            return getters.moreTwentyStu.length;
        },
        //  获取大于age岁的人信息
        moreAgeStu(state) {
            //  返回一个函数
            return function(age) {
                return state.students.filter(s => {
                    return s.age > age;
                })
            }
        }
    }
})

全局拿取数据

<p>{{ $store.getters.powerCounter }}</p>
<p>{{ $store.getters.moreTwentyStu }}</p>
<p>{{ $store.getters.moreTwentyStuLength }}</p>
<p>{{  $store.getters.moreAgeStu(20) }}</p>

同步操作:mutations

//  要点1:定义常量引入
//  要点2:需要通过commit提交常量

1.定义常量

//  mutations-type.js
export const INCREMENT = "increment";
export const DECREMENT = "decrement";
export const ADDCOUNTER = "addcounter";
export const ADDNUM = "addNum";

2.导入store文件和需要提交常量的文件

import {
  INCREMENT,
  DECREMENT,
  ADDCOUNTER,
  ADDNUM,
} from "./mutations-types.js";

3.vue文件通过commit提交常量

addNum() {
    this.$store.commit(INCREMENT)
},
subNum() {
    this.$store.commit(DECREMENT)
},
    
//  携带参数,正常提交
addCounter1(num) {
    this.$store.commit(ADDCOUNTER, num)
}
//  携带参数,对象提交
addCounter2(num) {
    this.$store.commit(从这开始{
        type: ADDNUM,
        num
    }到这结束为payload)
}

4.vuex接收常量和参数

const store = new Vuex.Store({
    state: {
        counter: 0,
        students: [
            {name: "swk", age: 19},
            {name: "zbj", age: 22},
        ]
    },
    mutations: {
        [INCREMENT](state) {
            state.counter++;
        },
        [DECREMENT](state) {
            state.counter--;
        },
        [ADDCOUNTER](state, num) {
            state.counter += num;
            console.log(num);// 此时num是一个数字
        },
        [ADDNUM](state, payload) {
            state.counter += payload.num;
            console.log(payload);// 此时payload是对象
        }
    }
})

异步操作:actions

//  要点1:需要通过dispatch提交常量
//  要点2:actions内部需要通过context.commit提交同步操作

store-index.js文件

//  需求:3秒钟以后修改name="zbj"
const store = new Vuex.Store({
    state: {
        info: [
            name: "swk",
            age: 22,
            height: 1.88
        ]
    },
    actions: {
        aUpdate(context) {
            //  模拟异步操作
            setTimeout(() => {
                //  通过commit提交同步
                context.commit(mUpdate);
            }, 3000)
        }
    },
    mutations: {
        mUpdate(state) {
            state.info.name = "zbj";
        }
    }
})

vue文件

methods: {
    updateClick() {
        //  dispatch提交异步
        this.$store.dispatch("aUpdate")
    }
}

执行异步操作时,可以使用Promise让携带信息和回调函数更加优雅

//  vue
methods: {
    ybUpdate() {
        this.$store
          .dispatch(从这开始{
            type: "aUpdate",
            info: {
              name: "zbj",
              age: 33,
              address: "glz"
            }
          }到这结束是payload)
          .then((res) => {
            console.log(res);
          });
    }
}

//  index.js
actions: {
    aUpdate(context) {
        //  Promise
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                //  提交同步
                context.commit("mUpdate");
                //  打印携带信息
                console.log(payload);
                //  执行resolve
                resolve("我是请求到的参数");
            }, 2000)
        })
    }
},
mutations: {
    mUpdate(state) {
        state.XXX = "修改信息"
    }
}

二级模块:modules

//  modules中可以有新的模块(state, actions, mutations, getters)
//  vue
btnClick() {
    //  dispatch提交异步
    this.$store.dispatch("aupdateName");
}

//  index.js
const moduleA = {
    state: {
        name: "zhangsan"
    },
    actions: {
        //  三秒后name = "lisi"
        //  接收异步
        aupdateName(context) {
            setTimeout(() => {
                //  commit提交同步
                context.commit(从这开始{
                    type: "mupdateName",
                    name: "lisi"
                }到这结束是payload)
            }, 3000)
        }
    },
    mutations: {
        //  接收同步
        mupdateName(state, payload) {
            state.name = payload.name;
        }
    },
    getters: {
        //  一个参数state调用模块内部state数据
        fullname1(state) {
            return state.name + "111"
        },
        //  两个参数,getters可以调用其他getters
        fullname2(state, getters) {
            return getters.fullname1 + "222"
        },
        //  三个参数rootState可以获取根部state内部数据
        fullname3(state, getters, rootState) {
            return getters.fullname2 + rootState.counter;
        }
    }
}

const store = new Vue.Store({
    state: {
        counter: 1
    },
    modules: {
        //  定义a模块
        a: moduleA,
    }
})

调用

//  使用modules中的state
<p>{{ $store.state.a.name }}</p>

//  使用modules中的getters
<p>{{ $store.getters.fullname1 }}</p>
<p>{{ $store.getters.fullname2 }}</p>
<p>{{ $store.getters.fullname3 }}</p>

总结

//  1.state内部保存数据,可以是数字,字符串,数组,对象等
//  2.mutations提交同步操作,通过this.$store.commit()提交
//  3.actions提交异步操作,先通过this.$store.dispatch()提交给actions内部,然后再通过context.commit()提交给mutations内部
//  4.getters为计算属性,内部第二个参数为getters,可以通过getters.XXX调用其他的getters
//  5.modules是子模块,里面还可以细分为更多的state, actions, mutations, getters
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • vuex是一个状态管理模式,通过用户的actions触发事件,然后通过mutations去更改数据(你也可以说状态...
    Ming_Hu阅读 2,099评论 3 3
  • 1. Vuex介绍和作用 1.1 Vuex 能做什么? 官方解释:Vuex 是一个专为 Vue.js应用程序开发的...
    itlu阅读 918评论 1 8
  • 1.安装Vue 依赖包 npm install vuex@3 --savevue2 只能用vuex的3版本vue3...
    洪锦一阅读 359评论 0 0
  • 一、vuex 1. 概念 Vuex 是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间数据的共享。 ...
    大刀劈向鬼子阅读 390评论 0 0
  • vuex vue 专用 状态管理模式 采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的...
    前端菜菜1号阅读 432评论 0 0

友情链接更多精彩内容