如何将Vue.prototype迁移到单独的文件中



我有几个函数要放在Vue.prototype中但我不想把main.js搞得一团糟我试着移植像这样的原型

//main.js
import "./vue-extensions/prototypes";

//prototypes.js
import Vue from "vue";
export default new Vue.prototype({
$appName = "myName",
});

但是使用这个我有一个错误`ERROR编译失败,出现1个错误下午6:35:11中的错误/src/vue-extensions/prototypes.js

语法错误:D:\Projects\FrontEnd\gta\src\vue-extensions\prototypes.js:意外的令牌(3:19(

1|从";vue";;2|导出默认的新Vue.prototype({

3|$appName="myName";,

@/src/main.js 14:0-37@多(webpack(-dev服务器/客户端?http://192.168.3.200:8080&sockPath=/sockjs-node(webpack(/hot/dev-server.js./src/main.js`

好吧,语法错误-对象文字中的赋值语句。

您不想实例化任何东西,所以不要使用new。您不想导出任何可以在main中导入的内容,所以不要使用export default。只需将修改原型对象的代码放在模块中,而不做其他事情:

//prototypes.js
import Vue from "vue";
Vue.prototype.$appName = "myName";
Vue.prototype.$assetsResolution = document.body.clientWidth * devicePixelRatio <= 1920 && document.body.clientHeight * devicePixelRatio <= 1080 ? 1080: 2160

另一种选择是,仍然在main.js中进行赋值,但在单独的模块中定义所有值:

//main.js
import prototypeExtensions from "./vue-extensions/prototypes";
Object.assign(Vue.prototype, prototypeExtensions);
//prototypes.js
import Vue from "vue";
export default {
$appName: "myName",
$assetsResolution: document.body.clientWidth * devicePixelRatio <= 1920 && document.body.clientHeight * devicePixelRatio <= 1080 ? 1080: 2160,
};

最新更新