Vue3在setup組合式API中使用全局掛載的屬性詳解
vue2中使用的方式
中我們通常在main.js文件中使用Vue.prototype 來綁定全局屬性,之后使用this來調(diào)用。
//在main.js文件 import Vue from 'vue'; import axios from 'axios'; Vue.prototype.$axios = axios; //在其它組件使用,直接用this調(diào)用 this.$axios
Vue3中使用provide 和 inject 來全局掛載(推薦)
在main.js文件中使用,如下
import { createApp } from 'vue'
import App from './App.vue'
import * as echarts from 'echarts';
let app = createApp(App);
// 全局掛載echarts
app.provide('$echarts',echarts);
app.mount('#app')在其它組件中使用(目前Vue3中該使用setup組合式API)
<script setup>
import { inject, onMounted } from "vue";
//導(dǎo)入掛載的echarts
const echarts = inject("$echarts");
onMounted(() => {
let myChart = echarts.init(document.getElementById('main'));
console.log(myChart);
});
</script>vue3組合式里面(不推薦)
vue3全局掛載屬性方式要通過globalProperties,
//vue3 main.js文件
import { createApp } from 'vue'
import App from './App.vue'
import * as echarts from 'echarts';
let app = createApp(App);
//全局掛載echarts屬性
app.config.globalProperties.$echarts = echarts;
app.mount('#app')調(diào)用的方式
<script setup>
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance();
//調(diào)用
proxy.echarts
</script>注意:
這種方式非常不好,Vue3官網(wǎng)中強(qiáng)烈建議不要把它當(dāng)作在組合式 API 中獲取 this 的替代方案來使用。
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Vue3中reactive丟失響應(yīng)式的問題解決(避大坑!)
這篇文章主要給大家介紹了關(guān)于Vue3中reactive丟失響應(yīng)式的問題解決,vue3中reactive定義的引用類型直接賦值導(dǎo)致數(shù)據(jù)失去響應(yīng)式 ,需要的朋友可以參考下2023-07-07
關(guān)于Vue中img動態(tài)拼接src圖片地址的問題
這篇文章主要介紹了關(guān)于Vue中img動態(tài)拼接src圖片地址的問題,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-10-10
vue使用element-plus依賴實現(xiàn)表格增加的示例代碼
這篇文章主要為大家詳細(xì)介紹了vue使用element-plus依賴實現(xiàn)表格增加,文中示例代碼講解的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2023-12-12
Pycharm中開發(fā)vue?element項目時eslint的安裝和使用步驟
這篇文章主要介紹了Pycharm中開發(fā)vue?element項目時eslint的安裝和使用,本文通過示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-05-05
vue實現(xiàn)的上拉加載更多數(shù)據(jù)/分頁功能示例
這篇文章主要介紹了vue實現(xiàn)的上拉加載更多數(shù)據(jù)/分頁功能,涉及基于vue的事件響應(yīng)、數(shù)據(jù)交互等相關(guān)操作技巧,需要的朋友可以參考下2019-05-05

