【问题标题】:Hiding Element Based on Route Path or Params in VueVue中基于路由路径或参数隐藏元素
【发布时间】:2017-05-21 15:14:12
【问题描述】:

我正在尝试根据路线是否在给定路径上来隐藏主应用导航栏。

在我的 App.vue 组件中,在 created() 方法中。我确实检查了路线是否是 x || y,如果其中任何一个为真,我将我的 Vuex 状态 show 设置为假。如果是这两条以外的其他路线,我设置show = true

然后在我的模板中我这样做

<template>
    <div id="app">
      <navigation v-show="show"></navigation>
      <router-view></router-view>
    </div>
</template>

我在 Vuex 工具中注意到我的突变甚至没有注册,所以我不确定为什么会这样。它们是否需要成为行动?这是我的完整代码。

<template>
    <div id="app">
      <navigation v-show="show"></navigation>
      <router-view></router-view>
    </div>
</template>

<script>
import Navigation from './components/Navigation/Navigation'
import { firebaseAuth } from './firebase/constants'
import store from './store/index'

export default {
  name: 'app',
  components: {
    Navigation
  },
  computed: {
    show () {
        return store.state.navigation.show
    }
  },
  created() {

    // Checks for a user and dispatches an action changing isAuthed state to true. 

    firebaseAuth.onAuthStateChanged(user => {
      console.log(store.state.authentication);
      console.log(user);
      store.dispatch('checkUser', user);
    }); 

    // Check if given route is true, if it is then hide Nav. 

    if (this.$route.path === "/dashboard/products" || this.$route.path === "/dashboard/settings") {
        store.commit('hideNav');
        } else if (this.$route.path !== "/dashboard/products" || this.$route.path !== "/dashboard/settings") {
        store.commit('showNav');
    }

  }
};

</script>

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    这可能不起作用,因为 created 在创建实例后仅调用一次。但是当路由更改时,它不会被调用,因此不会触发您期望在路由更改时触发的突变,而不是这个,您可以在路由上放置一个watch,所以在每次路由更改时,您可以检查是否是否显示您的导航栏,如下所示;

    工作小提琴:http://jsfiddle.net/ofr8d85p/

    watch: {
       $route: function() {
        // Check if given route is true, if it is then hide Nav. 
        if (this.$route.path === "/user/foo/posts") {
            store.commit('SHOWNAV');
            } else  {
            store.commit('HIDENAV');
        }
      }
    },
    

    【讨论】:

      猜你喜欢
      • 2021-03-10
      • 2016-09-16
      • 1970-01-01
      • 1970-01-01
      • 2018-05-24
      • 1970-01-01
      • 2021-09-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多