美文网首页
uniapp 全局变量的几种方式

uniapp 全局变量的几种方式

作者: 缘之空_bb11 | 来源:发表于2024-01-09 14:41 被阅读0次

    参考官网文档

    1. 直接在 Vue.prototype 上挂载, 然后在页面中直接使用

    在 main.js 中挂载属性/方法

    // 挂载变量字符串
    Vue.prototype.websiteUrl = 'http://uniapp.dcloud.io';  
    // 挂载变量函数表达式
    Vue.prototype.now = Date.now || function () {  
        return new Date().getTime();  
    };  
    // 挂载可传参的函数表达式
    Vue.prototype.isArray = Array.isArray || function (obj) {  
        return obj instanceof Array;  
    };
    
    

    可在页面中直接使用:

    this.websiteUrl         // 获取网站
    this.now()                 // 获取时间戳 
    this.isArray([1,2,3])       // 判断是否是数组  
    
    
    2. 公用模块(类似于原生开发的工具类)
    • 在根目录下创建 common 目录.并建立 public.js 文件
      在其定义的变量和方法,需要通过 export default 导出,供其他页面的使用
      示例:
    const apiUri = 'https://api.jisuapi.com/news/get?channel=头条&start=100&num=20&appkey=66487d31a1xxxxxx';
    
    const sayHi = function(){
        console.log('hello corley')
    }
    
    export default {
        apiUri,
        sayHi
    }
    
    • main.js 中挂载该文件
      示例:
    import common from '@/common/public.js'; // 引入
    
    Vue.prototype.$Common = common // 挂载 (注意: Vue.prototype.自定义方法名称 = Common ), $只是起到标识区分的效果,没有其他意思)
    
    
    • 子页面调用
      示例:
    this.$Common.sayHi() // 在调用时: this.自定义方法名称.sayHi()
    
    3.globalData

    在App.vue声明全局变量, 使用globalData属性
    示例:

    export default {
        globalData: {
        text: 'text'
        },
        onLaunch: function() {
        console.log('App Launch')
        },
        onShow: function() {
        console.log('App Show')
        },
        onHide: function() {
        console.log('App Hide')
        }
    }
    
    

    使用:

    赋值:getApp().globalData.text = 'test'
    取值:getApp().globalData.text      // 'test'
    
    4. 使用Vuex

    简书文档
    官方文档

    HBuilderX 2.2.5+起,支持vue和nvue之间共享

    • 基本结构

    使用 Vuex 需要遵守的规则:

    1.应用层级的状态应该集中到单个 store 对象中。
    2.提交 mutation 是更改状态的唯一方法,并且这个过程是同步的。
    3.异步逻辑都应该封装到 action 里面。

    State: 用来定义初始化数据变量, 只能访问数据
    不可直接对 state 进行更改,需要通过 Mutation 方法来更改.

    data() {
        unit : '岁'
    },
    
    // 计算属性
    computed: {
           // 单独直接获取
        countSingle2() {
        return store.state.count
        },
             // 能够获取自己 data 中的数据
        addCount2() {
           return  store.state.count + this.unit
        },
    }
    

    mapGetters 辅助获取

    // 使用 mapState 辅助获取
            ...mapState({
                 // 直接返回 store 中的 count 
                 countSingle1: state => state.count,
                     // 能够获取自己 data 中的数据
                 addCount1: function(state){
                     return state.count + this.unit
                 },
                  // 获取对象
                 infoStr: state => state.info
            }),
    

    Getter: 可以认为是 store 的计算属性. 只能访问数据
    如果 store中state上数据,在对外提供的时候,需要做一层包装,那么,推荐使用getters,相当于computed 属性,如果需要使用 getters 则用 this.$store.getters.xxx

    computed: {
         // 直接获取 
        todos() {
            return store.getters.doneTodos
        },
    }
    

    mapGetters 辅助获取

    computed: {
        / / 辅助获取,
        ...mapGetters(['doneTodos']),
    }
    

    Mutation: 同步方法,然后在修改数据
    Vuex中store数据改变的唯一方法就是mutation
    vuex mutations 中,必须是同步函数,不支持异步操作,所有的异步操作都放在 action 中

                      // 传参数,修改 count 变量
                     store.commit('add',500)
                     //传对象参数,修改 count 变量
                     store.commit('add',{amount : 10})
                     // 对象风格提交
                     store.commit({
                         type: 'add',
                         amount : 10
                     })
    
            add(state, n) {
                state.count += n
            },
            reduce(state, n) {
                state.count -= n
            },
            increase(state, n) {
                Vue.set(state.info, 'age', n)
            },
            change(state, obj) {
                state.info = obj
            },
    

    mapMutations 辅助函数提交

              // 在methods中,引入mutations中的increase方法
             // 调用时候,直接使用 this.reduce()即可
             // 只能用在无参数的状态下
            ...mapMutations(['reduce']),
    

    Action: 异步方法,然后在修改数据
    vuex mutations 中,不支持异步操作,所有的异步操作都放在 action 中;
    改变Vuex state中值,必须要通过mutations来处理,但是mutations中不支持异步操作,但是action中支持异步操作,所以必须要在action中结束异步操作,再调用mutations中事件来改变值


    var store = new Vuex.Store({
       state:{//相当于 data 存储数据,
             count:0;
       },
       mutations:{//相当于mothods方法 
          increate(){
          //如果子组件要调用 mutations 中的方法,只能使用this.$store.commit('方法名') — 这个方法最多传两个参数,如果多个参数,可以把它作为一个对象传过去**
             state.count++;
           }
       }, 
       getters:{//这个只负责对外提供数据,不负责修改数据,如果想修改 state 中数据,请找 mutations,这个方法和过滤器
       },
        action: {}// 异步操作,是为了让mutations中的方法能在异步操作中起作用。
    })
    
    

    相关文章

      网友评论

          本文标题:uniapp 全局变量的几种方式

          本文链接:https://www.haomeiwen.com/subject/orzondtx.html