gpt4 book ai didi

vue.js - 在vue/nuxt中导入文件js的位置

转载 作者:行者123 更新时间:2023-12-03 06:46:15 26 4
gpt4 key购买 nike

通常我使用带有功能的js代码在某些事件上运行。

现在,我正在使用nuxt.js,我想知道将文件放在哪里或如何创建在每个组件中使用这些功能的全局方法。
我可以在每个特定组件内编写所需的方法,但在该组件外将无法使用。

如何在vue / nuxt中做到这一点?

最佳答案

因此,在vue.js中做到这一点的一种方法是使用mixins,在nuxt中,您也可以使用mixins,然后应将它们注册为插件,但首先:

非全局mixins

为您的mixins创建一个额外的文件夹。例如在/mixins/myMixin.js中

export default {
methods: {
commonMethod() {
console.log('Hello')
}
}
}

然后导入布局,页面或组件,并通过mixins对象添加它:
<script>
import myMixin from '~/mixins/myMixin.js'

export default {
mixins: [myMixin]
}
</script>

全局mixins

例如在一个新文件plugins / mixinCommon.js中:
import Vue from 'vue'

Vue.mixin({
methods: {
commonMethod() {}
}
})

像这样在 nuxt.config.js中包含文件: plugins: ['~/plugins/mixinCommon']
之后,您将拥有到处可用的方法,并使用this.commonMethod()在此处调用该方法。但是这里有来自vue.js文档的建议:

Use global mixins sparsely and carefully, because it affects every single Vue instance created, including third party components. In most cases, you should only use it for custom option handling like demonstrated in the example above. It’s also a good idea to ship them as Plugins to avoid duplicate application.

关于vue.js - 在vue/nuxt中导入文件js的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57654077/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com