在UniApp中,可以使用全局变量、本地缓存和Vuex状态管理等方式来进行存值和取值。
App.vue文件的data中定义一个全局变量,在其他页面或组件中通过uni.$emit方法修改其值,并通过uni.$on方法监听值的变化。- // App.vue
- export default {
- data() {
- return {
- globalData: {}
- }
- }
- }
-
- // 页面或组件中获取全局变量
- export default {
- computed: {
- globalData() {
- return this.$root.globalData;
- }
- },
- methods: {
- updateGlobalData() {
- this.$root.globalData = { key: value };
- }
- }
- }
uni.setStorageSync方法将数据存储到本地缓存中,使用uni.getStorageSync方法从本地缓存中读取数据。- // 存值
- uni.setStorageSync('key', 'value');
-
- // 取值
- const value = uni.getStorageSync('key');
store目录下创建模块文件进行状态管理。通过commit方法提交一个mutation来更新状态,并通过getters获取状态值。- // store/module.js
- const state = {
- key: value
- };
-
- const mutations = {
- updateValue(state, payload) {
- state.key = payload;
- };
-
- const actions = {
- updateValue({ commit }, payload) {
- commit('updateValue', payload);
- }
- };
-
- const getters = {
- getValue(state) {
- return state.key;
- };
-
- export default {
- state,
- mutations,
- actions,
- getters
- };
-
- // 页面或组件中获取状态值
- import { mapGetters, mapActions } from 'vuex';
-
- export default {
- computed: {
- ...mapGetters(['getValue'])
- },
- methods: {
- ...mapActions(['updateValue'])
- }
- }
以上是UniApp中存值和取值的几种常用方式,你可以根据具体需求选择合适的方法来实现。