this.$router.query详解

发布时间:2023-05-23

一、什么是this.$router.query

this.$router.query是Vue.js中路由器对象router的一个属性,通过它可以获取到当前路由的查询参数。查询参数指的是URL中以问号“?”开始的字符串,通常用来传递不同页面之间的参数。例如,我们访问一个URL:http://mywebsite.com/products?id=123&name=abc,其中id和name就是查询参数。

二、如何使用this.$router.query

使用this.$router.query非常简单,只需要在需要获取参数的组件中调用即可。

export default {
  created () {
    console.log(this.$router.query);
  }
}

上述代码中,我们在组件的created生命周期函数中打印出this.$router.query,即可获取当前路由的查询参数。通常情况下,我们不会直接使用this.$router.query,而是将其解构出来保存在data中:

export default {
  data () {
    return {
      id: '',
      name: ''
    }
  },
  created () {
   const { id, name } = this.$router.query;
   this.id = id;
   this.name = name;
  }
}

上述代码中,我们通过解构this.$router.query,将id和name保存在组件的data属性中,方便后续使用。

三、this.$router.query的注意事项

1. URL中的查询参数需要进行编码

任何URL中的特殊字符都需要进行编码,否则可能会影响URL的解析和传递,造成一系列问题。例如上面提到的http://mywebsite.com/products?id=123&name=abc,在传递之前,需要对id和name进行编码。Vue.js提供了内置函数encodeURIComponent来进行编码:

let id = 123;
let name = 'abc';
window.location.href = 'http://mywebsite.com/products?id=' + encodeURIComponent(id) + '&name=' + encodeURIComponent(name);

2. this.$route和this.$router的区别

this.$route和this.$router都是Vue.js中路由器对象router的属性,但含义略有不同。this.$route表示当前路由信息对象,包括路径、参数、查询参数等等,而this.$router表示路由器对象,用来实现编程式导航。因此,this.$route.query和this.$router.query是不一样的。

3. 查询参数的类型问题

查询参数从URL中解析出来之后,都会变成字符串类型,即使它本来是数字或者布尔类型的。因此,在使用查询参数时,需要将其转换为正确的类型,否则可能会造成一系列问题。例如:

let id = this.$router.query.id; // '123'
console.log(id + 1); // '1231'

上述代码中,变量id的类型是字符串,因此对其进行加1操作时,实际上是字符串的拼接操作,不是数字的加法操作。正确的做法是将其转换为数字类型:

let id = parseInt(this.$router.query.id, 10); // 123
console.log(id + 1); // 124

四、常见问题解答

1. 如何获取路由参数而不是查询参数?

路由参数指的是路径中以冒号“:”开头的变量。例如,路由路径为/products/:id,表示id是一个路由参数。在路由跳转时,可以通过this.$router.params获取路由参数。例如:

export default {
  created () {
    console.log(this.$route.params.id);
  }
}

2. 如何在路由参数发生变化时重新渲染组件?

Vue.js提供了watch属性来监听data属性或者路由参数的变化,从而实现自动重新渲染组件。例如,我们可以使用以下代码来实现当路由参数id发生变化时,重新获取商品详情并渲染页面:

export default {
  data () {
    return {
      product: {}
    }
  },
  watch: {
    '$route.params.id' () {
      this.getProductDetail();
    }
  },
  methods: {
    getProductDetail () {
      // 获取商品详情
      // 更新组件的product属性
    }
  },
  created () {
    this.getProductDetail();
  }
}

3. 如何在路由参数不存在时显示默认值?

在访问某些页面时,我们可能需要设置默认的查询参数或者路由参数,以便提供更好的用户体验。下面的代码演示了如何为查询参数设置默认值:

export default {
  data () {
    return {
      type: 'all'
    }
  },
  created () {
    const { type } = this.$router.query;
    if (type) {
      this.type = type;
    } else {
      this.$router.replace({ query: { type: this.type } });
    }
  }
}

在上述代码中,如果URL中没有指定type查询参数,则会自动跳转到带有默认type参数值的URL。