Vue@2.7.x,使用组合式API(CompositionAPI)时,如何获取全局注册的属性或方法
-
前提
// 你已经在main.js中定义了全局属性,像vue2中定义的方式那样,全局可以通过this.$foo使用它
import Vue from 'vue'
Vue.prototype.$foo = foo
-
当使用
defineComponent
时
<script>
import { defineComponent, getCurrentInstance } from 'vue'
export default defineComponent({
setup(){
const { proxy } = getCurrentInstance()
const _foo = proxy.$foo // 获取并使用$foo
}
})
</script>
-
使用setup语法糖
<script setup>
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance()
const _foo = proxy.$foo // 获取并使用$foo
</script>