簡體   English   中英

Vuejs:單個文件組件的“模板或渲染函數未定義”

[英]Vuejs : “template or render function not defined” of a single-file-component

我嘗試導入文件夾的所有組件,並根據傳遞的道具顯示其中之一。

我將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單個文件組件require.context()導致錯誤: Failed to mount component: template or render function not defined.

我的require.context()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']
          }
        }
      }
    ]
  }
}

謝謝你的幫助 !

好的,如果您使用的是沒有模板編譯器的構建,則不能使用template屬性。 您需要做的是使用render函數將基本組件(其中帶有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如何保持navbar?

好吧,我終於解決了問題。

Linus Borg在https://forum.vuejs.org/t/vue-loader-with-webpack-not-supporting-commonjs-require/15014/4中說,使用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)解決了該問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM