2

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

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时,它可以工作。有人可以解释为什么以及如何解决这个问题吗?这里我有一个代码框

4

1 回答 1

6

我找了很长时间的解决方案,最后我得到了它。我使用vue了 from CDN,在这种情况下我应该说webpack使用 external Vue只需在webpack.config.js中进行此配置更改:

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

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

通过这些更改webpack捆绑组件并VueCDN. 我希望这个答案对其他人有所帮助。在这里,我已经进行了更改:代码和框

于 2021-02-12T11:04:16.593 回答