vue3怎么创建全局属性和方法

vue2.x挂载全局是使用Vue.prototype.$xxxx=xxx的形式来挂载,然后通过this.$xxx来获取挂载到全局的变量或者方法

在vue3.x这种方法显然是不行了,vue3中在setup里面我们都获取不到this,官方提供了globalProperties

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'

注意:千万不能这样子写:

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获取

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

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容