vue2和vue3配置全局自定义参数及vue3动态绑定ref
在 Vue2.x 中我们可以通过 Vue.prototype
添加全局属性 property。但是在 Vue3.x 中需要将 Vue.prototype
替换为 config.globalProperties
配置:
// Vue2.x Vue.prototype.$api = axios; Vue.prototype.$eventBus = eventBus; // Vue3.x const app = createApp({}) app.config.globalProperties.$api = axios; app.config.globalProperties.$eventBus = eventBus;
使用时需要先通过 vue 提供的 getCurrentInstance
方法获取实例对象:
// A.vue <script setup lang="ts"> import { ref, onMounted, getCurrentInstance } from "vue"; onMounted(() => { const instance = <any>getCurrentInstance(); const { $api, $eventBus } = instance.appContext.config.globalProperties; // do something }) </script>
vue3动态绑定ref
<div v-for="element in childApp" :key="element.key" class="appWrap" :ref="setChildAppRef"> {{element.content}} </div>
<script setup> let childAppRefs = [] let childApp = computed(() => store.state.childApp) const setChildAppRef = (el) => { if (el) { childAppRefs.push(el) } } </script>