在vue项目中使用vuex

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/x7418520/article/details/84064418

一个简单的例子

在vue项目中使用vuex

首先需要先了解vuex中的store,然后在store中又有state,getter,action,mutation这几个参数。

如何安装vuex,请查看vue官网安装vuex

下面演示一个简单的使用vuex的实例。

首先在state中,定义一个参数:

const state = {
    id: null,
}

我们按照习惯来写,新建一个mutation-type.js文件,里面存放,

export const SAVE_ID = 'SAVE_ID'

在mutaions中,定义方法:

import {RECORD_ADDRESS,} from './mutation-types.js'

[SAVE_ID](state, id) {
	  state.id = id;
},

现在就是保存store中的id值了

在需要的地方使用mapMutations辅助函数,映射为store.commit调用。
在这里需要注意一点,需要从vuex中引入这个辅助函数。

import {mapMutations} from 'vuex'

methods: {
    ...mapMutations([
        'SAVE_ID',
    ]),##这个函数建议放在methods中
}

然后在方法中调用,即可保存:

this.SAVE_PAPERID(this.id);

这时候已经可以使用$store.state.id,获取到id的值了,但是我又发现了一个问题,当页面刷新的时候,store中的值就消失了,这时查到解决方法。

将数据存放到localStorage中。

只需要在mutation中加入:

	[SAVE_ID](state, id) {
	  state.id = id;
	  window.localStorage.setItem('SAVE_ID', state.id);
    },

在获取数据的时候在加入一个判断:

computed: {
    id() {
    let localData = window.localStorage.getItem('SAVE_ID');
    if(this.$store.state.id==null && localData) {
      this.SAVE_ID(localData);
    }
    return this.$store.state.id;
  }
}

完成

参考博客:

https://vuex.vuejs.org/zh/guide/

https://blog.csdn.net/yiweichenji/article/details/80239511

猜你喜欢

转载自blog.csdn.net/x7418520/article/details/84064418