router-link标签Cannot read property '$route' of undefined"报错解决方法

报错代码:

<div class="card mb-3 px-3" v-for="item in data" v-bind:key="item.id">
  <router-link :to="{ path:'/exams/details', query:{ name: this.$route.query.name, id: this.$route.params.id} }" class="btn btn-outline-secondary btn-sm button-size">
            点击跳转
  router-link>
<div>

<script>
export default {
  data() {
	return {
	  plans: []
	}
  },
  async created() {
  	 //请求到数据时$route没有实例化
	 const plans = await this.$axios.get('/plans')
	 this.plans = plans.data
  }
script>

当放入v-for内时就会报如下错误:

TypeError: Cannot read property '$route' of undefined

报错原因:

this指向问题

解决方法:

去除$route前面的this

<div class="card mb-3 px-3" v-for="item in data" v-bind:key="item.id">
  <router-link :to="{ path:'/exams/details', query:{ name: $route.query.name, id: $route.params.id} }" class="btn btn-outline-secondary btn-sm button-size">
            点击跳转
  router-link>
<div>

你可能感兴趣的:(vue)