vuex五种基本对象
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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。
如对本文有疑问, 点击进行留言回复!!
vue中的@click.native.prevent,点击事件加上native.prevent究竟有什么用呢?
vue+element导出excel并通过xlsx-style修改样式
uniapp-iPhoneX和iPhoneX Max 的底部小黑条挡住底部tab
网友评论