uni-app教程三(全局模块util.js、全局变量、vuex)

1. 公用模块

1.1 定义一个专用的模块,用来组织和管理这些全局的变量,在需要的页面引入。

在 uni-app 项目根目录下创建 common 目录,然后在 common 目录下新建 util.js 用于定义公用的方法。

const baseUrl = 'https://ceshi2.dishait.cn/api/v1';  
const nowTime = Date.now || function () {
    
      
    return new Date().getTime();  
};  
export default {
    
      
    baseUrl,  
    nowTime,  
}  

1.2 接下来在 pages/index/index.vue 中引用该模块

<script>  
    import helper from '../../common/util.js';  
 
    export default {
    
      
        data() {
    
      
            return {
    
    };  
        },  
        onLoad(){
    
      
            console.log('nowTime:' + utils.nowTime());  
        },  
        methods: {
    
    },  
    }  
</script>  

小结

优点:这种方式维护起来比较方便;

缺点:需要每次都引入;

2. 挂载 Vue.prototype

将一些使用频率较高的常量或者方法,直接扩展到 Vue.prototype 上,每个 Vue 对象都会“继承”下来。

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

Vue.prototype.websiteUrl = 'https://ceshi2.dishait.cn/api/v1';  
Vue.prototype.nowTime = Date.nowTime || function () {
    
      
    return new Date().getTime();  
};  

2.2 在 pages/index/index.vue 中调用

<script>  
    export default {
    
      
        data() {
    
      
            return {
    
    };  
        },  
        onLoad(){
    
      
            console.log('now:' + this.nowTime());  
        },  
        methods: {
    
    }}  
</script>  

这种方式,只需要在 main.js 中定义好即可在每个页面中直接调用。

注意:

1、每个页面中不要在出现重复的属性或方法名。
2、建议在 Vue.prototype 上挂载的属性或方法,可以加一个统一的前缀。比如 $baseUrl,在阅读代码时也容易与当前页面的内容区分开。

3. Vuex

Vuex 是一个专为 Vue.js
应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

3.1 在 uni-app 项目根目录下新建 store 目录,在 store 目录下创建 index.js 定义状态值

const store = new Vuex.Store({
    
      
    state: {
    
      
        login: false,  
        token: '',  
        avatarUrl: '',  
        userName: ''  
    },  
    mutations: {
    
      
        login(state, provider) {
    
      
            console.log(state)  
            console.log(provider)  
            state.login = true;  
            state.token = provider.token;  
            state.userName = provider.userName;  
            state.avatarUrl = provider.avatarUrl;  
        },  
        logout(state) {
    
      
            state.login = false;  
            state.token = '';  
            state.userName = '';  
            state.avatarUrl = '';  
        }  
    }  
})  

3.2 在 main.js 挂载 Vuex

import store from './store'  
Vue.prototype.$store = store  

3.3 在 pages/index/index.vue 使用

<script>  
    import {
    
      
        mapState,  
        mapMutations  
    } from 'vuex';  
 
    export default {
    
      
        computed: {
    
      
            ...mapState(['token', 'userId', 'userName'])  
        },  
        methods: {
    
      
            ...mapMutations(['logout'])  
        }  
    }  
</script>  

猜你喜欢

转载自blog.csdn.net/weixin_43638968/article/details/109023307