Vue关于使用vue-router控制视图渲染的问题。

环境: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:有更好的思路吗?

先谢过...

阅读 4.8k
1 个回答

参照 @monster1935 的思路解决:

  export default {
    name: 'app',
    data () {
      return {
        showSide: true
      }
    },
    components: {
      TopBar,
      SideBar
    },
    methods: {

    },
    watch: {
      '$route': function(val, oldVal){
          /^\/stores/.test(val.path) ? this.showSide = false : this.showSide = true;
      }
    }
  }

更新回答 2017-02-24 16:34: 参照 @monster1935 的思路,解决了路由跳转('/' --> '/stores')时对SideBar的隐藏。但有一个遗漏,直接访问路径('/stores')时无法隐藏SideBar,原因是直接访问该路径时,没有触发App的watch。据此做了点改进,加了一个created钩子。

  export default {
    ...
    methods: {
      SideBarCtrl(path){
        /^\/stores/.test(path) ? this.showSide = false : this.showSide = true;
      }
    },
    created: function(){
      this.SideBarCtrl(this.$route.path)
    },
    watch: {
      '$route': function(val, oldVal){
        this.SideBarCtrl(val.path);
      }
    }
  }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题