时间:2022-10-07 11:28:25 | 栏目:vue | 点击:次
Vue3.x已经不支持直接Vue.prototype.$http = () => {}这种方式来挂载全局对象,这是由于globalVue不再是构造函数,因此不再支持该构造函数。


所以现在我们的办法就是这样
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
const vm = createApp()
let c=()=>{
console.log(1)
};
vm.config.globalProperties.$http =c;
vm.use(store).use(router).use(c).mount('#app');
this.$http
你不能使用Vue.use()或者Vue.extend()的方法,像有的插件,例如vue-layer,就不能在vue3.x中使用。
1.开发环境 vue3.0
2.电脑系统 windows10专业版
3.在使用vue开发的过程中,我们会有一些公用的属性和方法,我们一般为了方便使用会这个属性和方法挂载到全局,下面我来分享一下
4.vue2挂载方法
Vue.prototype.$http = http //在对应的组件中使用 this.$http //这种写法相信小火们很熟悉了,那么在vue3中怎么写呢?
4-1.vue3挂载并使用
// 全局挂载 const app = createApp(App) app.config.globalProperties.$Methods = Methods;
//在对应的组件中使用
import {
defineComponent,
ref,
getCurrentInstance,
onMounted,
reactive,
} from "vue";
//因为vue3是组合API,所以要引入对应的(getCurrentInstance)
// setup
//一个json数组去重
const { proxy }: any = getCurrentInstance();//关键代码
const $Methods = proxy.$Methods;//关键代码
const jsonarrreduce = reactive([
{ id: "1", name: "李白" },
{ id: "2", name: "杜甫" },
{ id: "3", name: "白居易" },
{ id: "4", name: "项羽" },
{ id: "5", name: "小米" },
{ id: "1", name: "红米" },
{ id: "1", name: "诺基亚" },
{ id: "2", name: "真我" },
]);
onMounted(() => {
console.log($Methods.JsonArrReduce(jsonarrreduce, "id"));
});
