我正在使用 Laravel与 Vue.js 和 Webpack/Laravel Mix。 我有应该使用 Mixins 的单个文件组件。 文件夹结构如下所示:
/app.js
/vue-components/Component.vue
/mixins/api/common.js
common.js 定义一个 mixin,如下所示:
export default {
// all content goes here
}
当我从app.js
和控制台导入它时.log它会显示数据:
import industries from "./mixins/api/common";
console.log(industries); // this shows the content
Vue.component(
'some-component',
require("./vue-components/Component.vue")
);
在 Component.vue 中,我使用mixins: [ industries ],
这给了我以下错误:
Component.vue?bb93:73 Uncaught ReferenceError: industries is not defined
问题 1:是否不可能全局声明 mixins 并从组件中引用它们?
为了解决这个问题,我尝试直接在组件中导入mixin,而不是全局app.js文件。 但是import industries from "./mixins/api/common";
在尝试使用 npm run 进行编译时,Component.vue
会抛出以下错误:
This relative module was not found:
* ./mixins/api/common in ./node_modules/babel-loader/lib?{"cacheDirectory":true,"presets":[["env",{"modules":false,"targets":{"browsers":["> 2%"],"uglify":true}}]],"plugins":["transform-object-rest-spread",["transform-runtime",{"polyfill":false,"helpers":false}],"babel-plugin-syntax-dynamic-import","webpack-async-module-name"],"env":{"development":{"compact":false}}}!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./resources/assets/js/vue-components/Component.vue
问题 2:如果我必须从单个文件组件中导入 mixin,路径应该是什么样子的?
就像在 Vue 文档中一样,你可以全局声明 mixin
//- build your mixin
const mixin = {
created: function () {
var myOption = this.$options.myOption
if (myOption) {
console.log(myOption)
}
}
}
Vue.mixin(mixin)
new Vue({
myOption: 'hello!'
})
// "hello!"
您还可以导入 mixin 以用于每个组件。
在上面的Component.vue
,导入路径不正确。 你应该做import industries from "../mixins/api/common"