uniapp使用vuex缓存数据
目录
前言
应用中一些不改变的数据,我们的做法一般是保存在缓存中,实现多次重复使用,从而减少对接口的请求次数,降低服务器的压力。vuex可以实现数据的缓存和更新。
一、vuex 是什么?
简单的说vuex是一种单应用页面中的一种缓存技术。
二、使用步骤
1.创建store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
// sex: ['男', '女', '未知']
name: 'sss',
isLogin: false, //判断是否已经登录 更新缓存
//
},
mutations: {
//修改缓存的方法
setLogin(state, payLoad) {
state.isLogin = payLoad
}
}
})
export default store
2.把store挂载到vue实例的原型上
在main.js中将store挂载的vue实例的原型上,便于全局访问
import App from './App'
import Vue from 'vue'
import store from './store/index.js'
Vue.prototype.$store = store //挂载到原型中
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
...App
})
app.$mount()
3.在state中属性访问数据
在vue页面中引入vuex
import {mapState} from 'vuex'
在computed中映射数据
computed: {
...mapState(['name', 'isLogin'])
}
页面直接访问
<view>{{name}}</view>
<view>{{isLogin}}</view>
3.更新缓存数据
在vue页面中引入vuex
methods: {
login() {
this.$store.commit('setLogin',!this.isLogin)
}
}
完整的vue代码如下:
<template>
<view class="content">
<view>{{name}}</view>
<view>{{isLogin}}</view>
<button type="primary" @click="login()"> 登录</button>
</view>
</template>
<script>
import {
mapState
} from 'vuex'
export default {
data() {
return {
}
},
computed: {
...mapState(['name', 'isLogin'])
},
methods: {
login() {
this.$store.commit('setLogin',!this.isLogin)
}
}
}
</script>
3.整体效果
总结
以上就是uniapp中使用vuex的简单方法,使用store极大的方便了数据的缓存和更新缓存,除此之外,也可以直接使用uni.setStorage(OBJECT)\uni.getStorageSync来保存和获取缓存数据。