【问题标题】:Unable to import Mixin from Single File Component in Vue.js无法从 Vue.js 中的单个文件组件导入 Mixin
【发布时间】:2018-11-11 15:19:23
【问题描述】:

我将 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 并在组件中引用它们吗?

为了解决这个问题,我尝试直接在组件中而不是全局 app.js 文件中导入 mixin。 但是Component.vue内的import industries from "./mixins/api/common";在尝试使用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,路径应该是什么样的?

【问题讨论】:

    标签: laravel-5 webpack vuejs2 vue-component


    【解决方案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"

    【讨论】:

    • 谢谢!我的导入路径不正确真的很愚蠢。谢谢。
    猜你喜欢
    • 2019-10-29
    • 1970-01-01
    • 2021-03-17
    • 2018-06-17
    • 2017-11-08
    • 1970-01-01
    • 1970-01-01
    • 2018-12-01
    • 2017-09-28
    相关资源
    最近更新 更多