Vue js rerender the same component when changing route

后端 未结 3 687
故里飘歌
故里飘歌 2020-12-15 23:12

I have one auth component that I am using both in the login and the signup route.

const routes = [{
  path     : \'/\',
  name: \'home\',
  component: Home
}         


        
3条回答
  •  青春惊慌失措
    2020-12-15 23:18

    The better way to do this is actually to bind the routes path to the router-view's key, i.e.

    
    

    Doing so will force Vue to create a new instance of the component.

    EDIT

    Updated to provide a meta key you could add which would allow you to disable the reuse of components only for the routes you require. this would need refining if you wanted to work with it on routes that are more than 1 level deep - but it gives you the idea.

    const Foo = {
      name: 'foo',
    	data () {
        	return {
            	inputText: '',
            }
        },
    	template: `
        	

    {{ $route.path }}

    `, } const Baz = { name: 'baz', data () { return { inputText: '', } }, template: `

    {{ $route.path }}

    `, } const routes = [ { path: '/foo', component: Foo, meta: { reuse: false }, }, { path: '/bar', component: Foo, meta: { reuse: false }, }, { path: '/baz', component: Baz }, { path: '/bop', component: Baz } ] const router = new VueRouter({ routes }) const app = new Vue({ router, data: { key: null, }, }).$mount('#app') router.beforeEach((to, from, next) => { if (to.matched.some(record => record.meta.reuse === false)) { app.key = to.path } else { app.key = null } next() })
    #content {
        position: relative;   
      height: 200px;
    }
    
    .box {
        position: absolute;
        top: 0;
        left: 0;
        width: 200px;
        height: 200px;
        background: rgba(0,0,0, 0.2);
        text-align: center;
        transform: translate3d(0, 0, 0);
    }
    
    
    
    

    Hello App!

    Go to Foo Go to Bar Go to Baz Go to Bop

    {{ key }}

    This then allows you to combine your router-view with Vues transition system so it becomes pretty awesome!

提交回复
热议问题