我将routes
添加到path
文件children
中:
path: '/warehouse/:id',
name: 'ShowWarehouse',
component: ShowWarehouse,
children: [{
path: 'edit',
name: 'EditWarehouse',
component: EditWarehouse
}
]
现在在组件ShowWarehouse
中,我拥有
<div v-if="!changeEdit">
<div v-if="warehouseData">
<div>Name: {{ warehouseData.warehouse.name }}</div>
<div>
<router-link
:to="{ name: 'EditWarehouse', params: {id: warehouseData.warehouse.id }}"
>Edit</router-link>
</div>
</div>
</div>
<router-view v-else></router-view>
当用户单击edit
按钮时,我需要加载组件EditWarehouse
,但是组件ShowWarehouse
必须消失,如果用户返回(没有/edit
),则组件{{ 1}}并加载组件EditWarehouse
。我在ShowWarehouse
中写方法:
watch
问题是,当用户位于watch: {
$route() {
if (this.$route.path == '/warehouse/' + id_get_from_API + '/edit') {
this.changeEdit = true;
} else {
this.changeEdit = false;
}
}
},
并单击重新加载页面(F5)时,Vue会加载组件mydomain.com/warehouse/23/edit
而不是加载ShowWarehouse
。
我使用EditWarehouse
。
答案 0 :(得分:0)
来自Vue.JS网站:“ Vue确实提供了一种更通用的方式来观察和响应Vue实例上的数据更改:监视属性。”刷新页面时,将不会执行watch()方法,因为它是一个新的Vue实例,并且Vue实例上的数据尚未更改。您可能应该使用其他模式来确定要显示的组件。 (https://vuejs.org/v2/guide/computed.html#Computed-vs-Watched-Property)
我建议将EditWarehouse作为通往ShowWarehouse的兄弟之路,并使其成为自己的组件 (您已经拥有了)。您在ShowWarehouse组件中的路由器链接可以保持不变。
代码段:
const ShowWarehouse = {
template: `<div><h1>ShowWarehouse</h1> <div v-if="warehouseData">
<div>Name: {{ warehouseData.warehouse.name }}</div>
<div>ID: {{ $route.params.id }}</div>
<div>
<router-link :to="{ name: 'EditWarehouse'}">Edit</router-link>
</div>
</div></div>`,
computed: {
warehouseData: function() {
let data;
let id = this.$route.params.id;
if (id) {
data = {
warehouse: {
name: 'Some Warehouse Name',
id: id
}
}
}
return data;
}
}
};
const EditWarehouse = {
template: "<h1>EditWarehouse [{{ $route.params.id }}]</h1>"
}
const router = new VueRouter({
routes: [{
path: '/warehouse/:id',
name: 'ShowWarehouse',
component: ShowWarehouse
},
{
path: '/warehouse/:id/edit',
name: 'EditWarehouse',
component: EditWarehouse
}
]
});
new Vue({
el: '#app',
router
});
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<div id="app">
<p>
<router-link :to="{ name: 'ShowWarehouse', params: { id: 123 }}">Go to Warehouse 123</router-link>
</p>
<router-view/>
</div>
这是一个具有相同代码的jsfiddle: https://jsfiddle.net/austinwasinger/oruswb3a/39/