网络编程
位置:首页>> 网络编程>> JavaScript>> vue3.0如何在全局挂载对象和方法

vue3.0如何在全局挂载对象和方法

作者:gis_rc  发布时间:2024-05-13 09:07:59 

标签:vue3.0,全局挂载,对象,方法

如何在全局挂载对象和方法

1.官方的说明

Vue3.x已经不支持直接Vue.prototype.$http = () => {}这种方式来挂载全局对象,这是由于globalVue不再是构造函数,因此不再支持该构造函数。

vue3.0如何在全局挂载对象和方法

2.更新后的挂载方法

这个是官网的说明

vue3.0如何在全局挂载对象和方法

所以现在我们的办法就是这样

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');

3.在全局使用

this.$http

4.但是应用中的this对象已经不再是一个Vue对象了

你不能使用Vue.use()或者Vue.extend()的方法,像有的插件,例如vue-layer,就不能在vue3.x中使用。

vue3全局挂载和使用

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"));
? ? });

vue3.0如何在全局挂载对象和方法

来源:https://blog.csdn.net/weixin_44265800/article/details/109121515

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com