【问题标题】:Where to import component in Vue?Vue 组件在哪里导入?
【发布时间】:2018-11-09 11:01:11
【问题描述】:

Vue 新手,从命令行处理一个脚手架项目。目前我有:

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>

还有home.vue

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

我正在尝试创建和导入chart-component.vue 以在home.vue 中使用,但不确定在哪里导入它。我已尝试将其添加到 main.jsApp.vue 中,但未成功。

chart-component.vue

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

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

            }
        }
    }
</script>

这似乎是一个简单的问题,但不确定如何解决。我最好的猜测是在App.vue 中导入它,并在name 下添加components { ChartComponent }。第二次尝试是将其导入main.js 并将ChartComponent 放入components: { App, ChartComponent }

【问题讨论】:

标签: javascript vue.js vuejs2


【解决方案1】:

Vue 3 script setup SFCs中导入组件变得更加容易

<script setup>
  import ChartComponent from './components/ChartComponent.vue'
</script>

<template>
    <ChartComponent />
</template>

【讨论】:

    【解决方案2】:

    我会将您的组件从 chart-component 重命名为 ChartComponent,因为破折号不是受支持的字符。 Vue 会根据需要正确地将名称转换为破折号,但是当您在代码中搜索组件时,使用一致的名称会有所帮助。

    无论如何。使用组件,需要先导入并定义它

    home.vue:

    <template>
        <ChartComponent></ChartComponent>
    </template>
    
    <script>
    import ChartComponent from './ChartComponent';
    
    export default {
      components: {
        ChartComponent
      }
    }
    </script>
    

    【讨论】:

      【解决方案3】:

      让它工作。因为我只需要在 home.vue 组件中本地使用它,所以我在添加的数据下将它导入到那里

      components: {
          'chart-component': ChartComponent
      }
      

      【讨论】:

        猜你喜欢
        • 2019-12-30
        • 2019-04-07
        • 1970-01-01
        • 2019-08-14
        • 2018-01-16
        • 1970-01-01
        • 1970-01-01
        • 2019-04-23
        • 2017-10-11
        相关资源
        最近更新 更多