vue2升级vue3:vue3创建全局属性和方法

vue2.x挂载全局是使用Vue.prototype.xxxx=xxxthis.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

posted @   zhoulujun  阅读(625)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享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、功能自动化测试
点击右上角即可分享
微信分享提示