v-if when router path changes

家住魔仙堡 提交于 2021-01-28 09:04:58

问题


may anyone help.

Is it possible to show some DOM element when route pat changes. Code

<div>
   <router-link v-if="$router.history.current['path'] !=='user/config'"
   class="btn btn-fill 
   btn-default" 
   tag="button" 
   to="/user/config">Change Config
    </router-link>
</div>

It works, but only when refreshing a page, how to listen to event of $router.history.current['path] changed?

Full component code:

    <template>
  <card class="card-user">
    <img slot="image" src="https://ununsplash.imgix.net/photo-1431578500526-4d9613015464?fit=crop&fm=jpg&h=300&q=75&w=400" alt="..."/>
       <router-link class="btn btn-fill btn-default" tag="button" to="/user/password-change">Change Passsword</router-link>
      </div>
      <div>
        <router-link class="btn btn-fill btn-default" tag="button" to="/user/password-change">Change Email</router-link>
      </div>
      <div>
        <router-link  v-if="v-if="$router.history.current['path'] !== '/user/config'"" class="btn btn-fill btn-default" tag="button" to="/user/config">Change Config</router-link>
      </div>
    </div>
  </card>
</template>
<script>
  import Card from 'src/components/UIComponents/Cards/Card.vue'
  export default {
    components: {
      Card
    },
    data () {
      return {
      }
    }
  }

</script>

But also this component is child User Thx


回答1:


I think your problem could be that you are using the same User component to render both /user and /user/config routes. If this is the setup, vue-router doesn't reload or re-render the component. To make the view react to changes in the path one option would be that of adding a parameter that changes. In this way, the router would handle the change (see vue-router docs on Dynamic Route Matching). If you don't want to change your routes to add this parameter, a trick is to add a changing :key to <router-view>:

<router-view :key="$route.fullPath"></router-view>

this will trigger a component full-lifecycle whenever the path changes (beware that this could impact performance for those components that wouldn't need a re-render). Then in your User component:

<template>
  ...
  <router-link  v-if="isNotInConfig()" class="btn btn-fill btn-default" tag="button" to="/user/config">Change Config</router-link>
  ...
</template>

<script>
export default {
  ...
  methods: {
    isNotInConfig() {
      return this.$router.history.current["path"] !== "/user/config";
    }
  },
  ...
};
<script>

Live demo

I've put together a full working live demo on codesandbox.io.



来源:https://stackoverflow.com/questions/49882850/v-if-when-router-path-changes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!