一、简介
对于我们常用的方法,可以使用原型挂载方便使用;其中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");