Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vue-router how to persist navbar?

I'm learning Vue coming from React, and wondering what the correct way to persist a navbar is - i have navigation on there with router links.

I have a navbar component with router-links which works, but it is reloading when heading to another route. Is there a way to persist it "outside" of the body components? Such as it isn't re-rendered when heading to a new route?

I tried putting it outside the router-view, but it does not render anywhere:

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

Same if it goes inside.

How do I persist the navbar? Should it be the parent of all components that go into the router, or what is best practice?

like image 226
cbll Avatar asked Nov 22 '17 10:11

cbll


1 Answers

Your navbar should render outside the router-view, here's how to set it up (you may have done a lot of this already).

First, start with a base app that serves up all your routes:

App.vue (Base App)

<template>
  <topnavbar />
  <router-view />
</template>

<script type="text/javascript">
  import topnavbar from './topnavbar.vue'
  export default{
    components:{
      topnavbar // register component
    }
  }

</script>

Now all you need to do is set up your router and mount the base App to your main Vue instance:

app.js

import Vue from 'vue'
import VueRouter from 'vue-router'
import App from ''./components/App.vue // import the base component

Vue.use(VueRouter);

// import views you want to serve up in `router-view`
import Foo from './components/views/Foo.vue' 
import Bar from './components/views/Bar.vue' 

const routes = [{
    path: '/foo',
    component: Foo
  },
  {
    path: '/bar',
    component: Bar
  },
]

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

new Vue({
  render: h => h(App), // mount the base component
  router
}).$mount('#app')

That should set everything up. Now, in order to make sure that the navbar doesn't refresh make sure you use router-link and not anchor tags:

Topnavbar.vue

<div id="topnav">
  <ul>
    <li><router-link to="foo">Foo</router-link></li>
    <li><router-link to="bar">Bar</router-link></li>
  <ul>
</div>

That should now serve up the components in your app without re-rendering topnavbar each time you navigate to a different page.

Here's the JSFiddle: https://jsfiddle.net/ukoebmwo/

like image 133
craig_h Avatar answered Nov 07 '22 02:11

craig_h