商城的网站建设,三步做一个抓娃娃机,wordpress 上级分类,wordpress 微信登录1.vuex的使用
一、uniapp中有自带vuex插件#xff0c;直接引用即可
二、在项目中新建文件夹store,在main.js中导入
在根目录下新建文件夹store,在此目录下新建index.js文件 index.js
import Vue from vueimport Vuex from vuexVue.use(Vuex)const store new Vuex.Store(…1.vuex的使用
一、uniapp中有自带vuex插件直接引用即可
二、在项目中新建文件夹store,在main.js中导入
在根目录下新建文件夹store,在此目录下新建index.js文件 index.js
import Vue from vueimport Vuex from vuexVue.use(Vuex)const store new Vuex.Store({state: {//公共的变量这里的变量不能随便修改只能通过触发mutations的方法才能改变},mutations: {//相当于同步的操作},actions: {//相当于异步的操作,不能直接改变state的值只能通过触发mutations的方法才能改变}
})
export default store
在main.js中导入挂载vuex
import Vue from vue
import App from ./App
import store from ./pages/store/index.js
Vue.prototype.$store storeVue.config.productionTip falseApp.mpType appconst app new Vue({store,...App
})
app.$mount()
2.使用
第一种方式this. s t o r e 直接操作例如当取值直接在页面中使用 t h i s . store直接操作 例如当取值直接在页面中使用this. store直接操作例如当取值直接在页面中使用this.store.state.变量名
第二种方法mapState, mapGetters, mapActions, mapMutations
templateview classcontent/view
/templatescriptimport { mapState, mapGetters, mapActions, mapMutations } from vuex//导入export default {data() {return {}},computed: { //computed中注册...mapGetters([text1]),...mapState([text1])}methods: {...mapMutations([]),...mapActions([])}}
/scriptstyle
/style
3.vuex持久化
问题
H5应用中存在Vuex中的数据在刷新页面后丢失了。
原因
Vuex的 store 中的数据是保存在运行内存中的当页面刷新时页面会重新加载 Vue 实例Vuex数据会重新初始化导致页面刷新Vuex中的数据丢失的问题。
解决
使用 vuex-persistedstate 插件 1、在项目目录下执行npm install --save vuex-persistedstate 2、修改store/index.js
import Vue from vue
import Vuex from vuex
import persistedState from vuex-persistedstateVue.use(Vuex)const store new Vuex.Store({plugins: [persistedState({storage: {getItem: key uni.getStorageSync(key),setItem: (key, value) uni.setStorageSync(key, value),removeItem: key uni.removeStorageSync(key)}})],state:{//存放状态username:,userid:},mutations:{//...},actions:{//...},//...
})export default store
使用后浏览器打开用控制台调试可看数据存放在 window.localStorage.vuex 这里其实就和调用uniapp提供的数据缓存API存放的数据位置一样了官方文档链接https://uniapp.dcloud.io/api/storage/storage.html
注意在APP-PLUS环境下这个数据在应用退出时默认不会被清空或者说初始化。 原文链接https://blog.csdn.net/Mr_Bobcp/article/details/125876232