vue原型挂载

一、简介

对于我们常用的方法,可以使用原型挂载方便使用;其中vue2与vue3所使用原型挂载方式各有不同;官网:vue-prototype-替换为-config-globalproperties

在 Vue 2 中, Vue.prototype 通常用于添加所有组件都能访问的 property。
在 Vue 3 等同于config.globalProperties。这些 property 将被复制到应用中作为实例化组件的一部分。

1、vue2挂载

文件main.js:

/** 挂载属性 */
import { initParams, initRules, initDicts, initPage } from "@/utils/init.js";
import { Toast } from "vant";

Vue.prototype.$init = {
  params: initParams,
  dicts: initDicts,
  rules: initRules,
  page: initPage,
};
Vue.prototype.$toast = Toast;
/** 挂载全局组件 */
// 文件上传组件
import FileUpload from "@/components/FileUpload";
Vue.component("FileUpload", FileUpload);

index.vue

// 挂载属性使用方法
onClick(){
	const params = this.$init.params();
	const dicts = this.$init.dicts();
	const rules = this.$init.rules();
	const page = this.$init.page();
    this.$toast("全局属性使用");
}

2、vue3挂载

main.ts
使用 provide 在编写插件时非常有用,可以替代 globalProperties

import { getAssetsFile } from "@/utils/tools";
import moment from "@/utils/moment";

const app = createApp(App);
// 原型挂载: app.config.globalProperties 与 app.provide
// 方法一:
app.config.globalProperties.$getAssetsFile = getAssetsFile;
// app.config.globalProperties.$moment = moment;

// 方法二:app.provide(key, value)
app.provide("$moment", moment); // 注入全局数据

index.vue

/** 属性使用 */
// 方法一:
const {
  proxy: {
    $getAssetsFile,
    //$moment
  },
} = getCurrentInstance();

// 方法二:
const $moment = inject("$moment");
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值