ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] ## 公用模块 注意 1. 这种方式只支持多个vue页面或多个nvue页面之间公用,vue和nvue之间不公用。 根目录创建 common/helper.js ``` const websiteUrl = 'http://uniapp.dcloud.io'; const now = Date.now || function () { return new Date().getTime(); }; const isArray = Array.isArray || function (obj) { return obj instanceof Array; }; export default { websiteUrl, now, isArray } ``` 使用 ``` <script> import helper from '../../common/helper.js'; export default { data() { return {}; }, onLoad(){ console.log('now:' + helper.now()); }, methods: { } } </script> ``` ## 挂载 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; }; ``` 使用 ``` <script> export default { data() { return {}; }, onLoad(){ console.log('now:' + this.now()); }, methods: { } } </script> ``` 注意: 1. 建议在 Vue.prototype 上挂载的属性或方法,可以加一个统一的前缀。比如 $url、global_url ## globalData 注意: 1. globalData支持vue和nvue共享数据 2. globalData是一种比较简单的全局变量使用方式 3. 如果需要把globalData的数据绑定到页面上,可在页面的onshow声明周期里进行变量重赋值 在 App.vue中 ``` <script> export default { globalData: { text: 'text' }, onLaunch: function() { console.log('App Launch') }, onShow: function() { console.log('App Show') }, onHide: function() { console.log('App Hide') } } </script> <style> /*每个页面公共css */ </style> ``` 使用 ``` 赋值:getApp().globalData.text = 'test' 取值:console.log(getApp().globalData.text) // 'test' ``` ## Vuex 根目录新建 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 = ''; } } }) ``` 在 main.js 中进行挂载 ``` import store from './store' Vue.prototype.$store = store ``` 在 vue 中使用 ``` <script> import { mapState, mapMutations } from 'vuex'; export default { computed: { ...mapState(['avatarUrl', 'login', 'userName']) }, methods: { ...mapMutations(['logout']) } } </script> ```