Vue 3 问题渲染子组件的子组件

Vue 3 problem rendering child of the child components

我使用 Webpack 5.21.2Webpack CLI 4.5.0 创建了一个 Vue 3.0.5 应用程序。我构建了一个全局组件 my-component.js:

import SecondComponent from './second-component.vue';
app.component('global-component', {
  template: `
    <div>
      <h1>Hi!</h1>
      <second-component></second-component>
    </div>
  `,
 components: {
   SecondComponent
 }
})

导入second-component.vue:

<template>
  <div>
    <div>{{someData}}</div>
    <third-component :name="helloWorld"></third-component>
  </div>
</template>

<script>
import ThirdComponent from './third-component.vue';
export default {
 name: 'second-component',
 components: {
   ThirdComponent 
 },
 data: function () {
   return {
     someData: 'Just some data!',
     helloWorld: 'Hello World!',
   }
  }
}
</script>

第三分量third-component.vue:

<template>
  <div>
    <div>{{name}}</div>
  </div>
</template>

<script>
export default {
  name: 'third-component',
  props: {
    name: String,
  }
}
</script>

这里是webpack配置webpack.config.js:

const { VueLoaderPlugin } = require('vue-loader');

module.exports = {
  mode: 'production',
  entry: {
    global_component: './global-component.js',
  },
  output: {
    path: `${__dirname}`,
    filename: '[name]_bundled.js'
  },
  resolve: {
   extensions: ['*', '.js', '.vue']
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        use: 'vue-loader'
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.css$/,
        use: [
          'vue-style-loader',
          'css-loader'
        ]
      }
    ]
  },
  plugins: [
    new VueLoaderPlugin()
  ]
}

我在 index.html 中使用的捆绑文件如下所示:

<body>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.0.5/vue.global.js"></script>
  <script>const app = Vue.createApp({});</script>
  <script type="application/javascript" src="global_component_bundled.js"></script>
  <div id="app">
    <global-component></global-component>
  </div>
  <script>app.mount("#app");</script>
</body>

我得到的问题是子组件的子组件没有渲染。就我而言,这是我要导入到 second-component.vue 中的组件 third-component.vue。但是,当我将组件 third-component.vue 直接用于 my-component.js 时,它会起作用。有人可以解释为什么以及我该如何解决?我这里有一个 codesandbox.

我找了很久的解决办法,终于找到了。我使用 CDN 中的 vue,在这种情况下我应该说 webpack 来使用外部 Vue。只需在 webpack.config.js:

中进行此配置更改
const { VueLoaderPlugin } = require('vue-loader');

module.exports = {
 ...
 externals: {
   // Here you tell webpack to take Vue from CDN
   vue: "Vue"
 },
 ...
}

通过这些更改 webpack 捆绑组件并从 CDN 中获取 Vue。我希望这个答案能帮助其他人。我已经在这里进行了更改:codesandbox.