vuex的使用案例


借鉴博客:

  https://segmentfault.com/a/1190000011914191

       https://blog.csdn.net/qq_43363884/article/details/95948884

一、vuex介绍:

  vuex:其实相当于一个存储数据的容器

  vuex有4个属性:state、getters、actions、mutations

state:    作用:用来自定义一些变量

getters:     作用:里面写用来获取state里数据的方法

actions:     作用:里面写api接口方法

mutations:  作用:用来触发事件,(就是在这里面写方法来使用getters属性,从而操作state里面的数据)

vuex容器里所有的操作,都要通过mutations来操作。

二、项目中怎么使用vuex

  1、创建一个store目录,里面创建一个store.js文件,store.js里面的内容可以设计成这样:

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);
let store = new Vuex.Store({
    // 1. state
    state:{
        city:"城市名"
    },

    // // 2. getters
    getters:{
        // 参数列表state指的是state数据
        getCityFn(state){
            return state.city;
        }
    },
    // 3. actions
    // 通常跟api接口打交道
    actions:{
        // 设置城市信息
        // 参数列表:{commit, state}
        // state指的是state数据
        // commit调用mutations的方法 
        // name就是调用此方法时要传的参数
        setCityName({commit,state}, name){
            // 跟后台打交道
            // 调用mutaions里面的方法
            commit("setCity", name);
        }
    },
    // 4. mutations
    mutations:{
        // state指的是state的数据
        // name传递过来的数据
        setCity(state, name){
            state.city = name;//将传参设置给state的city
        }
    }
});

export default store;

  2、然后在main.js中引用封装了vuex代码的store.js文件

import store from './store/store.js';  //引入后就可以有组件页面使用this.$store来调用vuex里面的方法了

new Vue({
router,
store,
render: h => h(App),
}).$mount('#app')

相关