Vue.js:在多个页面上使用的共享组件消失了

时间:2019-07-10 23:06:50

标签: javascript vue.js vue-component vue-router

现在,我正在使用vue-router在vue.js中编写一个单页应用程序。诸如主页,登录页面等页面均共享导航和页脚组件。但是,在几页上,我需要整个屏幕,以便导航和页脚不会显示。

因此,我决定嵌套组件,并在必要时包括导航和页脚组件。我现在的问题是,导航和页脚模板在所有页面上消失了。

编辑:可以在this Github repository中找到更完整的演示。

这是我正在使用的文件的简化版本:

index.html:

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

router.js:

import Homepage from './homepage.vue';
import SignIn from './signin.vue';

const router = new VueRouter({
  routes: [
    {path: '/', component: Homepage},
    {path: '/signin', component: SignIn},
    ]
})

homepage.vue和signin.vue组件:

<template>
  <navigation></navigation>  
    // some page-specific content
  <footer-vue></footer-vue>
</template>

<script>
import Navigation from './navigation.vue';
import Footer from './footer.vue';

export default {
  components: {
      'navigation': Navigation,
      'footer-vue': Footer,
  },
}
</script>

没有导航和页脚的组件:

<template> 
// some page-specific content
</template>

是否甚至可以通过这种方式嵌套组件?我希望有人能够为我指明正确的方向。

1 个答案:

答案 0 :(得分:2)

homepage.vuesignin.vue都有无效的模板。例如

<template>
    <navigation></navigation>
    <h1>The homepage</h1>
    <footer-vue></footer-vue>
</template>

不允许这样做,因为它有3个根节点。参见https://vuejs.org/v2/guide/components.html#A-Single-Root-Element

您需要包装它才能使其正常工作:

<template>
    <div>
        <navigation></navigation>
        <h1>The homepage</h1>
        <footer-vue></footer-vue>
    </div>
</template>

请注意,此限制不适用于功能组件,并且对于Vue 3中的所有组件也有望取消。

更令人担忧的是,您没有看到任何与此相关的错误消息。您确实需要研究一下,因为这表明您的开发设置有些不对劲。

您应该看到的错误消息示例:

new Vue({
  el: '#app',
  template: '<div></div><div></div>'
})
<script src="https://unpkg.com/vue@2.6.10/dist/vue.js"></script>
<div id="app">
</div>