1.main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import Antd from 'ant-design-vue';
import 'ant-design-vue/dist/antd.css';
import 'default-passive-events'
import Axios from 'axios';
const golBalTest = () =>{
console.log('测试全局挂载');
return '测试全局挂载';
}
const app = createApp(App)
// 挂载到vue原型上(方法1)
app.config.globalProperties.$axios = Axios;
app.config.globalProperties.$golBalTest = golBalTest;
app.config.globalProperties.$Test = "我在全局";
// 方法2
app.provide('root','root测试')
app.use(Antd);
app.use(store).use(router).mount('#app')
2.子组件中使用
<template>
<div>
<!-- {{ $Test }}
{{ $golBalTest() }} -->
<p>root:{{ root }}</p>
<ul v-for="(item, index) in dataList" :key="index">
<li>{{ item.title }}</li>
</ul>
</div>
</template>
<script>
import { reactive, ref, onMounted, inject, getCurrentInstance } from "vue";
import Axios from "axios";
export default {
name: "axios",
setup(props, context) {
let { attrs, slots, emit } = context;
// console.log("props", props);
// console.log("attrs", attrs);
const { proxy } = getCurrentInstance();
console.log("proxy", proxy.$axios);
let dataList = ref([]);
let root = inject("root");
onMounted(() => {
proxy.$axios
.get(
"http://vueshop.glbuys.com/api/home/category/menu?token=1ec949a15fb709370f"
)
.then((res) => {
console.log("res", res);
if (res.data.code == 200) {
dataList.value = res.data.data;
}
});
});
return {
dataList,
root,
};
},
};
</script>
<style scoped lang='scss'>
</style>