欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue3在setup組合式API中使用全局掛載的屬性詳解

 更新時間:2025年06月23日 09:20:47   作者:@窮且益堅,不墜青云之志  
這篇文章主要介紹了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)文章

最新評論