vue2升级vue3:vue3创建全局属性和方法
vue2.x挂载全局是使用Vue.prototype.xxx来获取挂载到全局的变量或者方法
在vue3.x这种方法显然是不行了,vue3中在setup里面我们都获取不到this,官方提供了globalProperties
1 2 3 4 5 6 | import { createApp } from 'vue' import App from './App' import router from '@router/index' const app = createApp(App).app.use(router).mount( '#app' ) app.config.globalProperties.$demoe = 'demo' |
注意:千万不能这样子写:
1 2 3 4 5 6 7 8 9 10 11 12 13 | createApp(App).config.globalProperties.$httpUrl = 'https://www.baidu.com' createApp(App).use(router) .use(store) .use(elementPlusUI) .mount( '#app' ) //或者是这样 const app = createApp(App) createApp(App).config.globalProperties.$httpUrl = 'https://www.baidu.com' app.use(router) .use(store) .use(elementPlusUI) .mount( '#app' ) |
第一种相当于我们直接调用了两次createApp(App),
最后调的那次里面压根就没有我们需要配置的全局变量,会返回undefined
在 compose api 如何用?
只需要从vue引入一个方法即可,不能在页面中使用this获取
1 2 3 4 5 6 7 8 9 10 11 12 | import { defineComponent, getCurrentInstance, onMounted } from "vue" export default defineComponent({ setup (props, {emit}) { // console.log(this) const { appContext : { config: { globalProperties } },proxy} = getCurrentInstance() const { ctx, proxy } = getCurrentInstance() console.log(globalProperties.$demo) return { proxy } } }) |
ctx和proxy都可以访问到定义的全局方法,但是ctx只能在本地使用,线上环境使用proxy
不管怎么样,在vue3项目,个人不推荐关在全局变量与属性。
参考文章:
vue3创建全局属性和方法 https://segmentfault.com/a/1190000040224048
vue3中挂载全局变量 https://blog.csdn.net/weixin_43090018/article/details/117222606
转载本站文章《vue2升级vue3:vue3创建全局属性和方法》,
请注明出处:https://www.zhoulujun.cn/html/webfront/ECMAScript/vue3/8861.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2021-07-25 web自动化测试(2):选择selenium优势?与PhantomJS/QTP/Monkey对比
2021-07-25 web自动化测试(1):再谈UI发展史与UI、功能自动化测试