使用路由獲取頁面參數(shù)
- 在路由中設(shè)置path:
{
path: '/detail/:id/',
name: 'detail',
component: detail,
meta: {
title: '詳情'
}
}
獲取參數(shù)
let id = this.$route.params.id
備注:
1、參數(shù)名需要保持一致
2呐芥、如果路由中沒有傳參(http://192.168.1.12:8080/#/detail),會報錯思瘟,頁面無法顯示,正常頁面為 http://192.168.1.12:8080/#/detail/234
如果有的參數(shù)可傳可不傳够话,可以使用光绕?傳參
例如:http://baidu.com/#/detail/?id=123
獲取的時候:
let id = this.$route.query.id
這樣即使取不到參數(shù),頁面也不會報錯
使用js獲取頁面參數(shù)
如果是在普通js文件中奇钞,想獲取url后面的參數(shù),可以新建一個工具類媒至,utils.js:
/* eslint-disable */
export default{
getUrlKey: function (name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null
}
}
在其他需要獲取參數(shù)的js中引入
import Vue from 'vue'
import utils from '../../assets/scripts/utils'
// Vue.prototype.$utils = utils // main.js中全局引入
let id = utils.getUrlKey('id')
console.log()
url為http://baidu.com/#/detail/?id=123時谷徙,可以得到id為123