user1670407
user1670407

Reputation:

Importing Vue Components with Webpack

I have a hello world Vue app setup with Webpack and have the initial App component working and mounted to body. Although within that App component I can't figure out how to use more components I made.

main.js

import Vue from 'vue'
import App from './app.vue'
    
new Vue({ 
  el: 'body',
  components: { App }
})

app.vue

<template>
  <div class="message">{{ message }}</div>
</template>

<script>
  export default {
    data () {
      return {
        message: 'Hello World'
      }
    }
  }
</script>

I have tried

import TopBar from './top-bar.vue'

In both main.js and the script section of app.vue then tried using

<top-bar></top-bar>

without luck.

I think I'm missing how to register the component properly, such as in the Vue docs it does:

Vue.component('top-bar', TopBar)

But I think when using webpack with vue-loader I need to do something different.

Upvotes: 32

Views: 49134

Answers (2)

Kevin Muchwat
Kevin Muchwat

Reputation: 1575

You can give it a suitable name in the components object as shown bellow

<template>
  <nav-bar></nav-bar>
</template>

<script>
import TopBar from './TopBar.vue'

export default {
  components: {
    'nav-bar': TopBar
  }
}
</script>

Upvotes: 5

Jeff
Jeff

Reputation: 25201

You can register it globally like you showed, or if you want to register it locally for use in a single component you need to add it to the components object of the Vue instance:

<template>
  <top-bar></top-bar>
  <div class="message">{{ message }}</div>
</template>

<script>
import TopBar from './top-bar.vue'

export default {
  components: {
    TopBar
  },
  data () {
    return {
      message: 'Hello World'
    }
  }
}
</script>

Upvotes: 41

Related Questions