在main.js中,使用app.config.globalProperties定义:
- // 添加属性aaa
- import { createApp } from 'vue'
- import App from './App.vue'
- import router from './router'
- import store from './store'
- let app = createApp(App)
- app.config.globalProperties.aaa = 123
- app.use(store).use(router).mount('#app')
使用:getCurrentInstance().appContext.config.globalProperties 获取全局定义的变量
注意:只能在setup或者生命周期函数中使用
- import { getCurrentInstance } from 'vue'
- export default {
- setup() {
- // getCurrentInstance 意思是获取当前组件的上下文 只能在setup或者生命周期函数中使用
- getCurrentInstance().appContext.config.globalProperties.aaa
- }
- }
参考:Vue3.0如何在setup中获取定义的全局方法_```木头人```的博客-CSDN博客
通过 ref
childRef.value的值包括在setup中返回的数据和prop传递过来的数据,等等...
- import { ref } from 'vue'
- import child from '@/components/child'
-
- export function useChild(newCb?: CallbackFn, editCb?: CallbackFn) {
- const childRef = ref<InstanceType<typeof child>>()
- childRef.value.dialogVisible = true
- }
- <template>
- <child ref=childRef>child>
- template>
-
- <script lang=ts>
- import { ref } from 'vue'
- import child from '@/components/child'
- export default defineComponent({
- name: 'user',
- components: { child },
- setup() {
- function useChild(newCb?: CallbackFn, editCb?: CallbackFn) {
- const childRef = ref<InstanceType<typeof child>>()
- childRef.value.dialogVisible = true
- }
- }
- })
- script>
3.组件中导入的对象变成响应式
包裹在computed中,将返回的ref对象绑定到template中