Vue解决同一页面跳转页面不更新

问题分析:路由之间的切换,其实就是组件之间的切换,不是真正的页面切换。这也会导致一个问题,就是引用相同组件的时候,会导致该组件无法更新。

方案一:使用 watch 进行监听

  watch: {
    /* ==== 解决详情页Url变化内容不更新问题 ==== */
    $route (to, from) {
      // 获取路由参数
      this.articleId = from.params.articleId
      // 从新初始化组件数据
      this._initData()
    }
  }

注意:这里有个问题,$router 是全局性的,即使添加在组件里面,使用此方法要添加判断

watch: {
    /* ==== 解决详情页Url变化内容不更新问题 ==== */
    $route (to, from) {
      // 判断是否为当前需求页面
      if (to.fullPath.indexOf('/articles-details') !== -1) {
        // 获取路由参数
        this.articleId = from.params.articleId
        // 从新初始化组件数据
        this._initData()
      }
    }
  }

方案二:router-view组件增加不同的 key值

<template>
  <div id="AppFG" @touchmove.prevent>
    <!--
    <transition name="router-fade" mode="out-in">
    </transition>
    -->
    <!--
      <router-view :key="key" />增加一个不同:key值,这样vue就会识别这是不同的<router-view />
    -->
    <keep-alive>
      <router-view :key="key"/>
    </keep-alive>
  </div>
</template>

<script>
export default {
  name: 'App',
  computed: {
    key () {
      return this.$route.path + Math.random()
    }
  }
}
</script>

方案三:销毁 router-link 组件,重新生成

<template>
  <div id="AppFG" @touchmove.prevent>
    <!--
    <transition name="router-fade" mode="out-in">
    </transition>
    -->
    <!--
      <router-view v-if="routerAlive" />增加一个不同v-if值,来先摧毁<router-link />,然后再重新创建<router-link />起到刷新页面的效果。
    -->
    <keep-alive>
      <router-view v-if="routerAlive"/>
    </keep-alive>
  </div>
</template>

<script>
export default {
  name: 'App',
  data () {
    return {
      routerAlive: true
    }
  },
  methods: {
    routerRefresh () {
      this.routerAlive = false
      this.$nextTick(() => {
        this.routerAlive = true
      })
    }
  }
}
</script>

 

posted @ 2018-10-17 10:28  victorlyw  阅读(2240)  评论(0编辑  收藏  举报