【问题标题】:Vuejs : "template or render function not defined" of a single-file-componentVuejs:单文件组件的“模板或渲染函数未定义”
【发布时间】:2018-05-08 21:35:51
【问题描述】:

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

我使用 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>

虽然我的Test 组件在docName'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']
          }
        }
      }
    ]
  }
}

感谢您的帮助!

【问题讨论】:

  • 你的主 vue 实例是什么样的?你定义了一个渲染函数吗?
  • 我编辑了帖子! ;) 我只使用不需要渲染函数的 *.vue 文件(据我所知),以及我的主 Vue 实例中的字符串模板。

标签: javascript webpack import vue.js vuejs2


【解决方案1】:

啊,好的,如果您使用的是没有模板编译器的构建,则不能使用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?

【讨论】:

  • 我很困惑,像你说的那样修复它不会改变任何东西:/ 顺便说一下,在我的 Webpack 配置(这是 Vue 的 webpack-template 之一)中,Vue 加载为 @ 987654326@,完整版(编译器+运行时)
  • 这些模板开箱即用,所以还有其他问题。很难知道确切的位置,但我会先从App.vue 中删除id="app",因为该ID 也将在index.html 中使用,这可能会导致冲突。
  • 是的,你是对的!我解决了这个问题,但这并不是真正破坏 docsComponents 的原因
  • 我已经测试过了,我很确定问题来自我的require.context() 代码块。我在主帖中解释过。
【解决方案2】:

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

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) 解决了这个问题。

【讨论】:

    猜你喜欢
    • 2018-07-16
    • 2020-02-02
    • 2018-06-07
    • 2021-01-23
    • 2019-06-17
    • 2019-12-08
    • 2018-10-29
    • 2017-02-13
    • 2020-04-26
    相关资源
    最近更新 更多