环境:Vue2.0 + vue-router + element-ui + 新手,
思路:想通过正则判断vue-router的$route.path来控制SideBar组件的渲染与否,具体代码如下:
App.vue
<template>
<div id="app">
<div class="warper">
<div class="header">
<TopBar></TopBar>
</div>
<el-row><el-col :span="2" >
<div class="grid-content bg-purple-dark">
<SideBar v-if="showSide"></SideBar> <!-- SideBar -->
</div>
</el-col>
<el-col :span="22">
<div class="grid-content bg-purple">
<div class="main-cntr">
<router-view></router-view>
</div>
</div>
</el-col></el-row>
</div>
</div>
</template>
export default {
name: 'app',
data () {
return {
showSide: true
}
},
components: {
TopBar,
SideBar
},
methods: {
},
beforeCreate(){
console.log(this.$route.path); // "/stores"
console.log(/^\/stores/.test(this.$route.path)); // true
if (/^\/stores/.test(this.$route.path)) { this.showSide = false }
console.log(this.showSide); // false
}
}
问题1:在组件中是否可以使用beforeCreate来创建钩子?文档都是在Vue实例中使用,但我在组件中使用也没有报错。
问题2:在beforeCreate中this.showSide = true, 但渲染出来的视图SideBar还是没有隐藏?可是console出来的结果显示已经设置this.showSide为false了
问题3:有更好的思路吗?
先谢过...
参照 @monster1935 的思路解决:
更新回答 2017-02-24 16:34: 参照 @monster1935 的思路,解决了路由跳转('/' --> '/stores')时对SideBar的隐藏。但有一个遗漏,直接访问路径('/stores')时无法隐藏SideBar,原因是直接访问该路径时,没有触发App的watch。据此做了点改进,加了一个created钩子。