以下内容若为特别申明不是一个vue页面中,均在一个页面中
1、获取本页data数据
data数据
onLoad: () => {
console.log(this);//会返回undefined
}
在其中不要使用箭头函数,箭头函数获取不到this值
onLoad: function(){
console.log(this);//使用普通函数即可获取到data的值,若想获取myName的值可写this.myName,即可获取
}
2、从本地缓存中同步获取数据
本页中
onLoad: function(){
let information = uni.getStorageSync('userInfo');
let information2 = JSON.parse(uni.getStorageSync('userInfo') || '[]');
this.myName = information2.nickName
console.log(this.myName) //可获取到个人信息的姓名
}
//以上两种都可以得到存在本地缓存中的个人信息,但是第一种information不可以将数据提出来使用;information2 可以拿出来使用。原因:存在本地时的数据转换成了字符串,直接去数据不转换则取出来的全部是字符串,而不是对象或数组等。
index.js中
//在store>index.js中存数据
import Vue from "vue"
import Vuex from "vuex"
Vue.use(Vuex)
const store = new Vuex.Store({
state:{
userInfo:{}
},
mutations:{
userInfo(state,data){
state.userInfo = data;
uni.setStorageSync('userInfo',JSON.stringify(data))//转换为字符串存储数据
}
},
getters:{},
actions:{
getUserInfo(context,data){
context.commit("userInfo",data)
}
}
})
export default store
存数据:uni.setStorageSync('userInfo',JSON.stringify(data))
取数据:let information = JSON.parse(uni.getStorageSync('userInfo') || '[]')
注意数据的转换