【问题标题】:Use vue component in other vue component file在其他 vue 组件文件中使用 vue 组件
【发布时间】:2018-03-05 04:22:36
【问题描述】:

我尝试在其他组件(App.vue)中使用一个 vue 组件(Global.vue),但是有

挂载组件失败:未定义模板或渲染函数

错误。

Global.vue

<template>
  <div class="global-view">
    <p>Global </p>
  </div>
</template>

<script>
export default {
  name: 'global'
}
</script>

App.vue

<template>
  <div id="app">
    <global></global>
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: 'app'
}
</script>

ma​​in.js

import Vue from 'vue'
import App from './App'
import router from './router'

Vue.component('global', require('./components/Global'))

Vue.config.productionTip = false

new Vue({
  el: '#app',
  router,
  template: '<App/>',
  components: { App }
})

【问题讨论】:

标签: vue.js


【解决方案1】:

您需要在要使用它的组件文件中导入该组件。

`从'./components/Global'导入全局

从那里你需要在你的组件选项中添加一个新的键来“注册”组件。

这是您希望应用组件的外观。

<template>
  <div id="app">
    <global></global>
    <router-view></router-view>
  </div>
</template>

<script>
import Global from './components/Global

export default {
  name: 'app'
  components: {
    'global': Global,
  }
}
</script>

&lt;global&gt;&lt;/global&gt;此时应该可以渲染了。

【讨论】:

  • OP 已经在使用 Vue.component 全局公开组件。
  • @Bert:OP 仍然需要注册该组件以供 new Vue 实例使用,方法是将其添加到 components 对象中。
  • 不,他没有,当它在全球注册时。
  • @Bert .vue 文件中的模板不会被编译为渲染函数,所以 Global.vue 需要预先了解自定义组件吗?以后在全球范围内注册它们无济于事。
  • 单个文件组件会被编译。它们被编译成一个对象,您可以或者全局注册,或者使用 components 属性在本地导入。请参阅此example。问题的真正问题是 import 和 require 之间的区别。
【解决方案2】:

我使用 import 而不是 require(在 main.js 中),它对我有用:

import Global from './components/Global.vue
Vue.component('global', Global)`

【讨论】:

    猜你喜欢
    • 2018-09-27
    • 1970-01-01
    • 1970-01-01
    • 2021-03-27
    • 2017-11-21
    • 2021-03-06
    • 2020-05-19
    • 2020-08-27
    • 2020-04-09
    相关资源
    最近更新 更多