不想使用vuex?vue2和vue3使用小型状态管理机,适合小型项目
vue2中的小型状态管理机:Vue.observable(),为了避免刷新页面数据丢失的结果我使用sessionStorage结合的方式
首先在app.vue中新建一个方法,再页面关闭卸载的时候将observable返回的对象存在本地sessionStorage
//App.vue
mounted() {
window.addEventListener('unload', this.saveState)
methods: {
saveState() {
sessionStorage.setItem('state', JSON.stringify(this.Store.state))
}
},
新建一个store文件夹,在文件夹中创建index.js文件,
import Vue from "vue";
const Store =Vue.observable({
state:sessionStorage.getItem('state') ? JSON.parse(sessionStorage.getItem('state')):{
show_loading:'',//存入控制loading的显示隐藏
}
})
Store.Action={
//显示loading
show_loading:function(val){
Store.state.show_loading = val
},
//隐藏loading
hidden_loading:function(val){
Store.state.show_loading = val
},
}
export default {
install(Vue){
Vue.prototype.Store=this.Store;
//初始化代码
},
Store
};
上面我们将observable返回的对象挂载在了vue的原型上,现在我们在main.js中引入到vue实例中
//main.js
import store from './store/index.js'
Vue.use(store);
new Vue({
store,
render: h => h(App),
}).$mount('#app')
vue页面使用
this.Store.Action.set_copytitle(this.title_nav_save)
this.Store.state.属性
vue3中的小型状态管理机:reactive
import { reactive } from 'vue'
let obj = reactive({ num: 520 })
let add = () => {
obj.num++
}
let edit = (newnum) => {
obj.num = newnum
}
export {
obj, add, edit
}
vue3中其他方式也基本和vue2一样的