Vuejs:单文件组件

时间:2017-11-24 22:08:52

标签: javascript webpack import vue.js vuejs2

我尝试导入文件夹的所有组件,并根据传递的道具显示其中一个组件。

我使用webpack和vue-loader导入我的所有组件。每个组件都是* .vue文件。

问题是通过导入存储在子文件夹中的一些组件,我在运行时遇到了这个错误:

[Vue warn]: Failed to mount component: template or render function not defined.

found in

---> <Test2>
       <VoneDocs> at src\components\VoneDocs.vue
         <App> at src\App.vue
           <Root>

在研究和@craig_h的帮助后,我发现问题来自我导入文件的方式:

<template>
  <transition name="fade">
  <div class="vone-docs" v-if="docName !== undefined">
    <component :is="docName"/>
  </div>
  </transition>
</template>

<script>
import Test from '../assets/docs/Test';

// import all docs (*.vue files) in '../assets/docs'
let docsContext = require.context('../assets/docs', false, /\.vue$/);
let docsData = {}; // docsData is {...<filenames>: <components data>}
let docsNames = {};
let docsComponents = {};
docsContext.keys().forEach(function (key) {
  docsData[key] = docsContext(key); // contains [{<filename>: <component data>}]
  docsNames[key] = key.replace(/^\.\/(.+)\.vue$/, '$1'); // contains [{<filename>: <component name>}]
  docsComponents[docsNames[key]] = docsData[key]; // contains [{<component name>: <component data>}]
});

export default {
  name: 'vone-docs',

  props: ['page'],

  components: {
    ...docsComponents,
    Test
  },

  computed: {
    docName () {
      return this.page;
    },

    docFileName () {
      return './' + this.docName + '.vue';
    },

    docData () {
      return docsData[this.docFileName];
    }
  },

  beforeRouteUpdate (to, from, next) {
    if (to.path === from.path) {
      location.hash = to.hash;
    } else next();
  },

  mounted () {
    console.log(docsComponents);
  }
};
</script>

TestdocName时(因为它是直接导入的),我的'test'组件成功显示,而导入require.context()的每个其他Vue单文件组件都会导致错误:Failed to mount component: template or render function not defined.

我的require.context()是否有任何错误?

这是我的webpack配置(除了使用raw-loader和html-loader,它与Vue webpack-template的配置相同)。

// webpack.base.conf.js
'use strict'
const path = require('path')
const utils = require('./utils')
const config = require('../config')
const vueLoaderConfig = require('./vue-loader.conf')

function resolve (dir) {
  return path.join(__dirname, '..', dir)
}

module.exports = {
  context: path.resolve(__dirname, '../'),
  entry: {
    app: './src/main.js'
  },
  output: {
    path: config.build.assetsRoot,
    filename: '[name].js',
    publicPath: process.env.NODE_ENV === 'production'
      ? config.build.assetsPublicPath
      : config.dev.assetsPublicPath
  },
  resolve: {
    extensions: ['.js', '.vue', '.json'],
    alias: {
      'vue$': 'vue/dist/vue.esm.js',
      '@': resolve('src'),
    }
  },
  module: {
    rules: [
      ...(config.dev.useEslint? [{
        test: /\.(js|vue)$/,
        loader: 'eslint-loader',
        enforce: 'pre',
        include: [resolve('src'), resolve('test')],
        options: {
          formatter: require('eslint-friendly-formatter'),
          emitWarning: !config.dev.showEslintErrorsInOverlay
        }
      }] : []),
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: vueLoaderConfig
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        include: [resolve('src'), resolve('test')]
      },
      {
        test: /\.(png|jpe?g|gif)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },
      // Art SVG are loaded as strings. Must be placed in the html with `v-html` directive.
      {
        test: /\.raw\.svg$/,
        loader: 'raw-loader'
      },
      // Icon SVG are loaded as files like regular images.
      {
        test: /\.icon\.svg$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('media/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(html)$/,
        use: {
          loader: 'html-loader',
          options: {
            attrs: [':data-src', 'img:src']
          }
        }
      }
    ]
  }
}

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

好的,如果您在没有模板编译器的情况下使用构建,则不能使用template属性。您需要做的是使用渲染函数将基本组件(其中包含router-view的组件)安装到主视图实例:

import App from './components/App.vue'

new Vue({
  el: '#app',
  router,
  render: h => h(App) // This mounts the base component (App.vue) on to `#app`
})

请记住,您的基本组件也应该是.vue文件。

我在前几天写了一篇关于设置Vue SPA的相当详细的答案,可以帮助你:vue-router how to persist navbar?

答案 1 :(得分:0)

好的,我终于解决了这个问题。

https://forum.vuejs.org/t/vue-loader-with-webpack-not-supporting-commonjs-require/15014/4中,Linus Borg说vue-loader并没有规范化出口。

let docsData = {};

function importAllDocs (r) {
  r.keys().forEach(function (key) {
    docsData[key.replace(/^\.\/(.+)\.vue$/, '$1')] = r(key).default;
  });
}

importAllDocs(require.context('../assets/docs', true, /\.vue$/));

访问r(key).default代替r(key)解决了问题。