在vue.js中添加新组件?

Jos*_*ers 4 vue.js

我想在我的组件文件中创建一个组件,然后在我的基本应用程序中包含它(如以前的ng-include)。

我的App.vue看起来像这样:

   <template>
    <div id="app">
     <div class="container-fluid">
      <div class="row>
       <navigation></navigation>
      </div>
      <div class="row">
       <router-view></router-view>
      </div>
     </div>
    </div>
   </template>

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

   <style>
    #app {
    font-family: 'Avenir', Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #2c3e50;
    margin-top: 60px;
    }
   </style>
Run Code Online (Sandbox Code Playgroud)

我的main.js文件如下所示:

   import Vue from 'vue'
   import App from './App'
   import VueRouter from 'vue-router'
   import homepage from './components/homepage'
   import navigation from './components/navigation'

   Vue.use(VueRouter)

   const routes = [
    { path: '/', component: homepage}
   ]

   const router = new VueRouter({
    routes,
    mode: 'history'
   })

   new Vue({

    el: '#app',
    template: '<App/>',
    components: { 
     App, navigation 
    },
    router
   }).$mount('#app')
Run Code Online (Sandbox Code Playgroud)

navigation.vue:

    <template>
     <div>
      <p>test</p>
     </div>
    </template>

    <script>
     export default {
      name: 'navigation'
     }
    </script>
Run Code Online (Sandbox Code Playgroud)

当我运行上面的代码时,我得到:

[Vue警告]:未知的自定义元素:-您是否正确注册了组件?对于递归组件,请确保提供“名称”选项。

在发现

---> src / App.vue

我知道如何添加vue.component,但是我想要的是一个外部组件,例如主页,它是从components文件夹中提取的,并包含在基本应用程序中。

Lor*_*rti 5

要在新的Vue实例中使用组件,或者使用(如您所说的)VUE.component,或者应该导入并注册该组件。参见https://vuejs.org/v2/guide/components.html#Local-Registration,您可以在App.VUE中尝试使用:

    <template>
    <div id="app">
     <div class="container-fluid">
      <div class="row>
       <navigation></navigation>
      </div>
      <div class="row">
       <router-view></router-view>
      </div>
     </div>
    </div>
   </template>

   <script>
    import navigation from './components/navigation.vue'

    export default {
     name: 'app',
     components:{
        navigation
     }
    }
   </script>

   <style>
    #app {
    font-family: 'Avenir', Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #2c3e50;
    margin-top: 60px;
    }
   </style>
Run Code Online (Sandbox Code Playgroud)

其中navigation.vue组件可能类似于:

<template src="template.html"></template>
<script>
  export default {
    data(){
      return {} 
    }

  }
</script>
Run Code Online (Sandbox Code Playgroud)