2

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 }
})
2
  • See this github.com/sagalbot/vue-select/issues/127 - perhaps the require statement is casuing the problem, Johnathan suggests using import instead. Commented Sep 24, 2017 at 2:55
  • @RichardMatsen yeah, import works Commented Sep 24, 2017 at 7:38

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

5 Comments

OP is already exposing the component globally using Vue.component.
@Bert: OP still needs to register that component to be used by the new Vue instance by adding it to the components object.
No, he does not, when it is registered globally.
@Bert Doesn't template in .vue files get compiled to a render function, so Global.vue needs to know about custom components up front? Registering them later, globally, will not help with that.
Single file components do get compiled. They get compiled into an object that you can either register globally, or import locally using the components property. See this example. The real issue in the question is the difference between import and require.
1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.