我有一个在登录和注册路径中都使用的身份验证组件。
const routes = [{
path : '/',
name: 'home',
component: Home
}, {
path : '/signin',
name: 'signin',
component: Auth
},
{
path : '/signup',
name: 'signup',
component: Auth
}];
例如,如果我在登录页面问题是如果我在文本输入中键入一些内容并转到注册,文本仍然存在,我如何强制组件重新初始化?
最佳答案
更好的方法实际上是将路由路径绑定(bind)到路由器 View 的键,即
<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',
data () {
return {
inputText: '',
}
},
template: `
<div class="box">
<h1>{{ $route.path }}</h1>
<input type="text" v-model="inputText">
</div>
`,
}
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);
}
<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>
然后,这允许您将路由器 View 与 Vues 转换系统结合起来,使其变得非常棒!
关于javascript - Vue js 在更改路由时重新渲染相同的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40884023/