• uniapp存值和取值方法


    UniApp中,可以使用全局变量、本地缓存和Vuex状态管理等方式来进行存值和取值。

    1. 全局变量:可以在App.vue文件的data中定义一个全局变量,在其他页面或组件中通过uni.$emit方法修改其值,并通过uni.$on方法监听值的变化。
    1. // App.vue
    2. export default {
    3. data() {
    4. return {
    5. globalData: {}
    6. }
    7. }
    8. }
    9. // 页面或组件中获取全局变量
    10. export default {
    11. computed: {
    12. globalData() {
    13. return this.$root.globalData;
    14. }
    15. },
    16. methods: {
    17. updateGlobalData() {
    18. this.$root.globalData = { key: value };
    19. }
    20. }
    21. }
    1. 本地缓存:可以使用uni.setStorageSync方法将数据存储到本地缓存中,使用uni.getStorageSync方法从本地缓存中读取数据。
    1. // 存值
    2. uni.setStorageSync('key', 'value');
    3. // 取值
    4. const value = uni.getStorageSync('key');
    1. Vuex状态管理:UniApp内置了Vuex状态管理库,可以在store目录下创建模块文件进行状态管理。通过commit方法提交一个mutation来更新状态,并通过getters获取状态值。
    1. // store/module.js
    2. const state = {
    3. key: value
    4. };
    5. const mutations = {
    6. updateValue(state, payload) {
    7. state.key = payload;
    8. };
    9. const actions = {
    10. updateValue({ commit }, payload) {
    11. commit('updateValue', payload);
    12. }
    13. };
    14. const getters = {
    15. getValue(state) {
    16. return state.key;
    17. };
    18. export default {
    19. state,
    20. mutations,
    21. actions,
    22. getters
    23. };
    24. // 页面或组件中获取状态值
    25. import { mapGetters, mapActions } from 'vuex';
    26. export default {
    27. computed: {
    28. ...mapGetters(['getValue'])
    29. },
    30. methods: {
    31. ...mapActions(['updateValue'])
    32. }
    33. }

    以上是UniApp中存值和取值的几种常用方式,你可以根据具体需求选择合适的方法来实现。

  • 相关阅读:
    word怎么公式求平均值
    (续)SSM整合之springmvc笔记(域对象共享数据)(P136-138)
    Python习题详解
    webpack定制化 环境配置[开发环境、生产环境、前后端半分离环境]
    Mysql临时表创建查询修改
    7-42 子集和问题——组合子集
    python考前复习(90题)
    [HTML]HTML5新增标签
    【使用 Python 实现算法】01 语言特性
    品牌线上布局思路有哪些,品牌策略分析!
  • 原文地址:https://blog.csdn.net/m0_73481765/article/details/133043728