首页 > 解决方案 > 如何从url获取参数并在vue中显示

问题描述

我有一个网址: http://localhost:8080/Currency?currency=RMB 我想获取货币参数,即RMB

在:

created(){
    this.currencyParam = this.$route.query.currency;
    console.log(curr: ${this.currencyParam});
}

我可以进去curr: RMBF12 - consoleF12 -Vue我得到了currency:undefined

在我的模板中:

<template v-else>
          <gateway
            :currency="this.$route.query.currency"
          />
</template>

我收到一个错误:

渲染错误:“ TypeError:无法读取在和中找到的未定义的属性'$route'F12 -Vue我仍然得到currency:undefined

标签: vue.js

解决方案


您可以添加一个监视属性,该属性将允许您侦听查询参数中的更改

data () {
  return {
   currencyParam = null
  }
},
watch: {
    '$route.query.currency': function () {
       if(this.$route && this.$route.query.currency) { // if not undefined
            console.log(`curr: ${this.$route.query.currency}`);
            this.currencyParam = this.$route.query.currency;
       }
    }
  }

也像这样更改您的模板;

<template>
   <gateway v-if="currencyParam" :currency="currencyParam" />
</template>

推荐阅读