vue——vuex基本使用

vuex 是用来解决 vue 多个组件之间的数据同步的问题

vuex包含 state 、getters 、mutations、actions,一个组件通过 mutations 来修改数据,另一个组件可以通过 getters 来获取数据的副本,组件之间相互订阅了数据

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

//注册vuex插件
Vue.use(Vuex)

//初始化user 如果存在就设为localStorage中的user,如果不存在就初始化为空
const user=JSON.parse(localStorage.getItem('user'))||{userName:null,phone:null,email:null}
//1、创建一个仓库
export default new Vuex.Store({
    //仓库的原始数据,可以预设,也可以通过ajax想后台请求
    state:{  //属性
        user
    },
    //订阅数据变化 内容为方法
    getters:{   //属性
        user(state){
            return state.user
        }
    },
    //定于方法以改变数据,使用this.$store.commit('login')调用
    mutations:{  //方法
        //只能传两个参数,第一个参数为仓库对象,第二个参数设置为需要同步的参数,可以是数组或者JSON对象,使用this.$store.commit('login','login')
        login(state,payload){
            state.user=payload
            //把user信息存入到本地存储中
            localStorage.setItem('user',JSON.stringify(payload))
        },
        loginOut(state){
            state.user={userName:null,phone:null,email:null}
            localStorage.removeItem('user')
        }
    },

    // actions 也是一个一对多的功能,可以同时触发多个数据变化
    actions:{
        // CHUANGE_NUM(mutation){
        //     mutation.commit('changeC')
        //     mutation.commit('changeD')
        // }
        //等同于下面代码
        CHUANGE_NUM({commit}){
            commit('changeC')
            commit('changeD')
        }
    }
})

1、state 包含原始的数据,相当于一个仓库,用来存储数据,不可以直接修改

2、getters 是原始数据的副本,获取 state 的值,不可修改

3、mutations 用来修改state中的数据

4、actions 用来提交 mutations 修改过后的数据

在main.js入口文件中导入vuex配置文件,并在vue实例中添加store对象

import store from '../store/index.js'

new Vue({
  el: '#app',
  store,
  components: { App },
  template: '<App/>'
})

在vue组件中使用以下代码修改vuex中的state数据

this.$store.commit('login',user)//第一个参数为mutations 中的方法,第二个参数为login 方法的实参

猜你喜欢

转载自blog.csdn.net/YUHUI01/article/details/84112454