我有一个auth组件,我在登录和注册路由中都使用它.
const routes = [{ path : '/',name: 'home',component: Home },{ path : '/signin',name: 'signin',component: Auth },{ path : '/signup',name: 'signup',component: Auth }];
解决方法
更好的方法是将路由路径绑定到路由器视图的密钥,即
<router-view :key="$route.path"></router-view>
这样做会强制Vue创建组件的新实例.
编辑
更新为提供您可以添加的元键,允许您仅为所需的路由禁用组件的重用.如果你想在超过1级深度的路线上使用它,这将需要改进 – 但它给你的想法.
const Foo = { name: 'foo',data () { return { inputText: '',} },template: ` <div class="Box"> <h1>{{ $route.path }}</h1> <input type="text" v-model="inputText"> </div> `,} const Baz = { name: 'baz',} const routes = [ { path: '/foo',component: Foo,Meta: { reuse: false },},{ path: '/bar',{ 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.2); text-align: center; transform: translate3d(0,0); }
<script src="https://unpkg.com/vue/dist/vue.js"></script> <script src="https://unpkg.com/vue-router@2.0.3"></script> <div id="app"> <h1>Hello App!</h1> <p> <router-link to="/foo">Go to Foo</router-link> <router-link to="/bar">Go to Bar</router-link> <router-link to="/baz">Go to Baz</router-link> <router-link to="/bop">Go to Bop</router-link> </p> <div id="content"> <router-view :key="key"></router-view> </div> <pre>{{ key }}</pre> </div>
然后,您可以将路由器视图与Vues过渡系统结合使用,这样它就变得非常棒了!