方式一:使用依赖注入(provide/inject)(推荐)
在main.ts中进行挂载:
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
import { getAction } from 'index'
app.provide('getAction', getAction) // 将getAction方法挂载到全局
app.mount('#app')
在要使用的页面注入:
<script setup lang="ts">
import { inject } from 'vue'
const getAction: any = inject('getAction')
</script>
方式二:使用 app.config.globalProperties 和 getCurrentInstance() (不推荐)
在main.ts中进行挂载:
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
import { getAction } from 'index'
app.config.globalProperties.$getAction = getAction
app.mount('#app')
<script setup lang="ts">
import { getCurrentInstance } from 'vue'
const { proxy }: any = getCurrentInstance()
console.log('proxy:', proxy)
console.log('getAction:', proxy.$getAction)
</script>
vue 中的 getCurrentInstance 方法返回了 ctx 和 proxy,控制台打印 ctx 和 proxy 发现和 vue2.x 中的 this 等同,习惯使用 this 的朋友可以用 proxy 进行替代。
但是不推荐使用,不推荐原因其实在官网中已经说的很明白了
官方解说: 在 setup() 内部,this 不会是该活跃实例的引用(即不指向vue实例),因为 setup() 是在解析其它组件选项之前被调用的,所以 setup() 内部的 this 的行为与其它选项中的 this 完全不同。这在和其它选项式 API 一起使用 setup() 时可能会导致混淆。因此setup函数中不能使用this。所以Vue为了避免我们错误的使用,直接将setup函数中的this修改成了 undefined)
我理解: 在Vue3中,setup 在生命周期 beforecreate 和 created 前执行,此时 vue 对象还未创建,因此,无法使用我们在 vue2.x 常用的 this。在生产环境内可能会获取不到该实例!!,而且我们确实不应该用该方法去代替this
网友评论