当前位置: 移动技术网 > IT编程>脚本编程>vue.js > 解决vuex刷新状态初始化的方法实现

解决vuex刷新状态初始化的方法实现

2019年09月06日  | 移动技术网IT编程  | 我要评论

vuex五种基本对象

  • state:存储状态(变量)
  • getters:对数据获取之前的再次编译,可以理解为state的计算属性。我们在组件中使用$sotre.getters.fun()
  • mutations:修改状态,并且是同步的。在组件中使用$store.commit('',params)。这个和我们组件中的自定义事件类似。
  • actions:异步操作。在组件中使用是$store.dispath('')
  • modules:store的子模块,为了开发大型项目,方便状态管理而使用的。这里我们就不解释了,用起来和上面的一样。
npm install vuex -s // 安装vuex

src/store/index.js

import vue from 'vue'
import vuex from 'vuex'
import temp from '@/store/modules/temp'

vue.use( vuex ); // 挂载在vue

const store = new vuex.store({
  modules: {
    temp,
  }, state: {

  }, getters: {

  }, mutations: {

  },
});

export default store; // 抛出

src/store/modules/temp.js

const storage = sessionstorage
const tempinfo = {
  state: { // 设置全局访问的state对象
    tempdata: storage['set_temp_data'] ? json.parse(storage['set_temp_data']) : {}, // 设置初始化的值(storage中是否存在,存在则获取,不存在则默认赋值{})
  }, mutations: { // 自定义改变state初始值的方法,这里面的参数除了state之外还可以再传额外的参数(变量或对象);
    set_temp_data(state, tempdata) {
      state.tempdata = tempdata
    },
  }, actions: {
    setdata({ commit }, tempdata) {
      commit('set_temp_data', tempdata); // 同步操作
      storage.setitem('set_temp_data', json.stringify(tempdata))
    }
  }, getters: { // 实时监听state值得变化(最新状态)
    tempdata: (state) => {
      return state.tempdata
    }
  }
}
export default tempinfo;

main.js

import vue from 'vue'
import app from './app'
import router from './router'
import store from '@/store/index' //vuex 状态管理

vue.config.productiontip = false

/* eslint-disable no-new */
new vue({
 el: '#app',
 router,
 store, // 使用store
 components: { app },
 template: '<app/>'
})

src/index.vue

<template>
 <div class="move-forward">
   <div @click="click">点击改变vuex值</div>
</template>
<script>
  export default {
    methods: {
      click() {
        let aa = this.$store.getters.tempdata.aaa*1
        this.$store.dispatch('setdata', {"aaa": aa += 1})
      },
    }
  }
</script>

其他

当然还可以使用vuex-persistedstate、vuex-along等这些第三方插件。

npm i -s vuex-persistedstate或npm i -s vuex-along

import vue from 'vue'
import vuex from 'vuex'
import temp from '@/store/modules/temp'
import createpersistedsatte from 'vuex-persistedstate' // 引入

vue.use( vuex );

const store = new vuex.store({
  modules: {
    temp,
  }, state: {

  }, getters: {

  }, mutations: {

  },
  plugins: [createpersistedsatte()], // 挂载插件
});

export default store

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网