Vue3 在setup组合式API 中 使用全局挂载的属性

vue2中使用的方式

中我们通常在main.js文件中使用Vue.prototype 来绑定全局属性,之后使用this来调用

//在main.js文件
import  Vue  from 'vue';
import axios from 'axios';
Vue.prototype.$axios = axios;

//在其它组件使用,直接用this调用
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";

//导入挂载的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')

调用的方式

<script setup>
  import { getCurrentInstance } from 'vue'
 const { proxy } = getCurrentInstance();
 //调用
 proxy.echarts
</script>

注意:这种方式非常不好,Vue3官网中强烈建议不要把它当作在组合式 API 中获取 this 的替代方案来使用。

猜你喜欢

转载自blog.csdn.net/tengyuxin/article/details/125784648#comments_28368075