我正在使用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
和console.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";
中的Component.vue
在尝试使用npm run编译时会引发以下错误:
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,那么路径应该是什么样的?
答案 0 :(得分:1)
与Vue Document一样,您可以全局声明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"