解决使用$router.go(-1)时报错type check failed for prop “title”. Expected String with value “undefined”, got Undefined
这个问题出现的原因是我使用路由传参了,但是我在使用$route.go(-1)返回时,当前路由已经发生了变化,但是页面上还在获取title参数
路由设置
{
path: '/order/view/:title',
name: '预售单查看',
component: () => import('@/pages/order/bookingorder/view')
},
{
path: '/order/myorder',
name: '我的订单',
component: () => import('@/pages/order/myorder/myorder_list')
},
我的订单上面的跳转函数
lookHandler () {
let title = '预售单查看'
this.$router.push({
path: `/order/bookingorder/view/${title}`
})
},
editHandler () {
},
approvalHandler () {
let title = '预售单审批'
this.$router.push({
path: `/order/bookingorder/view/${title}`
})
},
页面
<template>
<div>
<a-card :bordered="false">
<common-header :title="title" :order-id="orderApply.orderNo"/>
<!--- 预售单审批,预售单查看页面 -->
<applybase :orderApply="orderApply"/>
<button-layout>
<template slot="action">
<span v-if="title === '预售单审批' ">
<a-button type="primary">审批通过</a-button>
<a-button type="danger">审批不通过</a-button>
</span>
<a-button @click="backHandler">返回</a-button>
</template>
</button-layout>
</a-card>
</div>
</template>
<script>
import commonHeader from '../../common/common_header'
import applybase from './applybase'
import buttonLayout from '@/pages/buttonlayout/buttonlayout'
export default {
name: 'bookingorderView',
props: {
},
components: {
applybase, commonHeader, buttonLayout
},
data () {
return {
title: '',
orderApply: {
}
}
},
methods: {
backHandler () {
this.$router.go(-1)
},
getTitle () {
this.title = this.$route.params.title
}
},
created () {
this.getTitle()
},
watch: {
$route: function (to, from) {
// 监听route参数变化,设置title值,防止报Undefined的错,重点是这里,确保点击返回按钮时不报错!!!!
// if (to.path !== '/order/myorder') {
this.title = to.params.title
// }
}
}
}
</script>
<style scoped>
</style>
这个问题的与路由传参有关,Vue官方文档上解释了当使用同一个路由时,组件会被复用,这也意味着组件的生命周期钩子不会再被调用,所以当只是路由参数发生变化时,created,updated等生命周期函数不会发生变化,所以不能够只在钩子函数里面获取参数,而是要监听路由,再来获取参数,这样当路由参数发生变化时页面才会刷新