vuex store的运用

vuex用来管理vue的所有组件状态。
首先下载vuex,”vuex”:”^3.0.1”,运用”vuex-persistedstate”来对数据进行缓存。下载”vuex-persistedstate”
在文件中引入:(新建一个store文件夹,在文件夹下的index.js文件进行如下编写)

import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
Vue.use(Vuex)

定义简单模块:

const module = {
    state: {
        user: {
            name: 'rookie'
        }
    },
    getters: {},
    mutations: {
        setUser(state, payload){
            if(payload.hasOwnProperty('name')){
                state.user.name = payload.name
            }
        }
    },
    plugins: [createPersistedState()]
}

上面是一个简单的vuex,在vuex中对应的store应用,在store中包含组件的共享状态state和改变状态的方法(暂且称作方法)mutations。注意state相当于对外的只读状态,不能通过store.state.user.name来更改,使用store.commit方法通过触发mutations改变state。
在页面中获取记录的值name为rookie:

mounted(){
    console.log(this.$store.state.user.name);
}

store.state为获取store中的值,此时在my页面中打印出来的值为rookie,而我们想要修改name的值,则需要借助store.commit方法来触发mutations:

this.$store.commit('setUser',{name: 'kuke_kuke'})

在mutations中找到setUser,第二个参数payload为传入的对象{name: ‘kuke_kuke’},调用方法hadOwnProperty来判断传入的对象是否有name属性,从而修改state中的值,此时在页面中再次打印user.name的值为’kuke _ kuke’。
最后导出模块:

const store = new Vuex.Store(module)
export default store

别忘记在main.js中获取模块并使用:

import store from './store'
new Vue({
    store
})

作者:rookie.he(kuke_kuke)
博客链接:http://blog.csdn.net/qq_33599109
欢迎关注支持,谢谢!

  • 7
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值