Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to import component in Vue?

New to Vue, working off a scaffolded project from the command line. Currently I have:

index.js

import Vue from 'vue'
import Router from 'vue-router'
import Home

from '../components/home'



Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home
    }
  ]
})

main.js

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


Vue.config.productionTip = false

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

App.vue

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

<script>
export default {
  name: 'App',
}
</script>

<style>
#app {
  // default styles are here
}
</style>

And home.vue

<template>
    <chart-component></chart-component>
</template>
// rest of home

I am trying to create and import chart-component.vue to use inside home.vue but not sure where to import it at. I've tried adding it in main.js and App.vue unsuccessfully.

chart-component.vue

<template>
    <div>
        <h1>Testing Chart Component</h1>
    </div>
</template>

<script>
    export default {
        name: 'chart',
        data() {
            return {

            }
        }
    }
</script>

This seems like a simple problem but unsure how to solve it. My best guess was importing it inside App.vue and adding a components { ChartComponent } underneath the name. Second attempt was importing it into main.js and putting ChartComponent inside components: { App, ChartComponent }.

like image 929
Vincent Nguyen Avatar asked May 30 '18 14:05

Vincent Nguyen


2 Answers

I would rename your component to ChartComponent from chart-component, as the dash is not a supported character. Vue will properly convert the name to dashes as needed, but when you're searching your code for components, it helps to have consistent names.

anyway. for using a component, you need to import it and define it first

home.vue:

<template>
    <ChartComponent></ChartComponent>
</template>

<script>
import ChartComponent from './ChartComponent';

export default {
  components: {
    ChartComponent
  }
}
</script>
like image 85
Daniel Avatar answered Oct 20 '22 13:10

Daniel


Got it to work. Since I only need it locally inside the home.vue component I imported it inside there under data I added

components: {
    'chart-component': ChartComponent
}
like image 41
Vincent Nguyen Avatar answered Oct 20 '22 15:10

Vincent Nguyen