Web 前端

vue 路由参数发生变化时响应操作

2021-04-06  本文已影响0人  时光觅迹

某些情况下,为了能尽量的使组件可重用,我们可能想要在类型差不多的两个链接跳转到同一个组件,然后这个组件根据路由的参数不同而加载不同的数据。

为了实现这个功能,我们可以在这个组件中监听路由的变化:

export default {
  name: "ArticleList",
  data() {
    return {
      articleList: []
    }
  },
  watch: {
    // 侦听路由器参数变化
    $route: {
      handler(newVal) {
        // newVal 是更新后的 $route 值
        console.log("router changed", newVal)
        if (newVal.query.data) {
            // 取出更新后的 $route 的query 参数:newVal.query
            // 再取出参数中 key 为 data 的值,然后再取出值里面的 url
          this.getArtices(newVal.query.data.url);
        }
      }
    }
  },
  methods: {
    getArtices(url) {
      this.$axios.get(url).then(res => {
        console.log("getArtices:", res);
        this.articleList = res.data;
      });
    }
  }
};
上一篇 下一篇

猜你喜欢

热点阅读