Use vue component in other vue component file

2019-04-14 12:46发布

I tried to use a vue component(Global.vue) in other component(App.vue), but there

Failed to mount component: template or render function not defined

error.

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>

main.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
2条回答
Juvenile、少年°
2楼-- · 2019-04-14 13:28

You need to import the component within the component file that you want to use it in.

`import Global from './components/Global'

From there you need to add a new key inside your components option that will "register" the component.

Here is what you want your app component to look like.

<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>

<global></global> should be able to render at this point.

查看更多
该账号已被封号
3楼-- · 2019-04-14 13:32

I used import instead of require(in main.js) and it works for me:

import Global from './components/Global.vue
Vue.component('global', Global)`
查看更多
登录 后发表回答