[英]How to import Library into Vue3 project
could someone help me import a library to my vue3 project so that I can use it in all components?...有人可以帮我将一个库导入我的 vue3 项目,以便我可以在所有组件中使用它吗?...
I'am trying to import 'moments.js' to my project我正在尝试将“moments.js”导入我的项目
import { createApp } from "vue"
import App from "./App.vue"
import moment from "moment"
const app = createApp(App)
app.use (moment)
app.mount("#app")
but when I try to console.log(this.moment)
from another component I get errors that this.moment
is not a function但是当我尝试从另一个组件
console.log(this.moment)
时,我收到this.moment
不是函数的错误
You can bind moment as a global property on the Vue instance by during the created
lifecycle hook in the like manner.您可以在
created
的生命周期挂钩期间以类似的方式将时刻绑定为 Vue 实例上的全局属性。
const { createApp } = require('vue');
import App from "./App.vue";
import moment from 'moment';
const MomentPlugin = function (Vue, options) {
Vue.mixin({
created: function () {
this.moment = moment
}
})
}
const app = createApp(App)
app.use(MomentPlugin).mount("#app");
moment
function is then available in template context or anywhere the Vue instance is available in scope. moment
函数随后在模板上下文中或 Vue 实例在范围内可用的任何地方可用。
For anyone stumbling onto this post.对于任何偶然发现这篇文章的人。 I changed the code to:
我将代码更改为:
import { createApp } from "vue"
import App from "./App.vue"
import moment from "moment"
const app = createApp(App)
app.provide("moment", moment)
app.mount("#app")
inside other components:在其他组件内部:
export default {
inject: ["moment"],
// Other code can now use "moment"
}
app.use()
is for adding Vue plugins to the app. app.use()
用于向应用程序添加 Vue 插件。 It should be possible to convert Moment.js to a plugin - see "Writing a plugin" in the documentation but it shouldn't be necessary.应该可以将 Moment.js 转换为插件 - 请参阅文档中的“编写插件”,但这不是必需的。
You can just import moment.js in any component where you want to use it and the bundling process will make sure that the code is not duplicated anywhere.您可以在要使用它的任何组件中导入 moment.js,并且捆绑过程将确保代码不会在任何地方重复。
I would try using this package https://www.npmjs.com/package/vue-moment as it is vue-specific.我会尝试使用这个包https://www.npmjs.com/package/vue-moment因为它是 vue 特定的。 It is a wrapper for moment.
它是暂时的包装。 Check the Readme file also for instructions.
还要检查自述文件以获取说明。 https://github.com/brockpetrie/vue-moment
https://github.com/brockpetrie/vue-moment
import Vue from 'vue'
import VueMoment from "vue-moment"
Vue.use(VueMoment));
Your case你的情况
import { createApp } from "vue"
import App from "./App.vue"
import VueMoment from "vue-moment"
const app = createApp(App)
app.use (VueMoment)
app.mount("#app")
You can use moment like this in any component.您可以在任何组件中使用这样的时刻。
methods: {
moment: function () {
return moment();
}
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.