JS獲取地址欄參數(shù)的兩種方法(原生、vue)
若地址欄URL為:code-nav/article/917?type=12&title=abc,我們要獲取到地址欄后面的的type和title參數(shù),如何才能拿到呢?
解決方案:
1.原生JS實現(xiàn):
1.1 采用正則表達(dá)式獲取地址欄參數(shù)(第一種方法)
//獲取地址欄參數(shù),key:參數(shù)名稱
function getUrlParams(key) {
let reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
let r = window.location.search.substr(1)
.match(reg);
if (r != null)
return unescape(r[2]);
return null;
}
let title = getUrlParams("title"); // abc
let type = getUrlParams("type"); // 121.2 傳統(tǒng)方法截取實現(xiàn)(第二種方法)
//獲取地址欄參數(shù)
function getUrlParams() {
let url = window.location.search; //獲取url中"?"符后的字串
let paramsObj = new Object();
if (url.indexOf("?") != -1) {
let str = url.substr(1);
str = str.split("&");
for (let i = 0; i < str.length; i++) {
paramsObj[str[i].split("=")[0]] = decodeURI(str[i].split("=")[1]);
}
}
return paramsObj;
}
let type = getUrlParams().type; // 12
let title = getUrlParams().title; // abc2.Vue框架實現(xiàn):
2.1 查詢參數(shù)獲?。▓鼍耙唬?/h3>
我們需要從地址code-nav/article/917?type=12&title=abc上拿到title的value abc。
<script setup>
import {useRouter} from 'vue-router'
const { currentRoute } = useRouter();
const route = currentRoute.value;
onMounted(()=>{
let type=route.query.type
console.log('type', type) // 12
})
</script>2.2 獲取路徑參數(shù)(場景二)
我們需要從地址code-nav/article/917上拿到917這個參數(shù)。
首先需要在router/index.js中定義好路由以及路徑參數(shù),如下代碼:
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/:id',
name: 'home',
component: () => import('../views/home.vue')
},
]
})
export default router接著就可以在home.vue組件中通過路由useRouter得到參數(shù),注意是route.params,如下代碼:
<script setup>
import {useRouter} from 'vue-router'
const { currentRoute } = useRouter();
const route = currentRoute.value;
onMounted(()=>{
let id=route.params.id
console.log('id', id) // 917
})
</script>到此這篇關(guān)于JS獲取地址欄參數(shù)的兩種方法(原生、vue)的文章就介紹到這了,更多相關(guān)JS獲取地址欄參數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
iscroll-probe實現(xiàn)下拉刷新和下拉加載效果
這篇文章主要為大家詳細(xì)介紹了iscroll-probe下拉刷新和下拉加載,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-06-06
JS函數(shù)參數(shù)的傳遞與同名參數(shù)實例分析
這篇文章主要介紹了JS函數(shù)參數(shù)的傳遞與同名參數(shù),結(jié)合實例形式分析了JS函數(shù)參數(shù)的傳遞與同名參數(shù)相關(guān)原理、使用技巧與操作注意事項,需要的朋友可以參考下2020-03-03
關(guān)于javascript document.createDocumentFragment()
documentFragment 是一個無父對象的document對象.2009-04-04
javascript的replace方法結(jié)合正則使用實例總結(jié)
這篇文章主要介紹了javascript的replace方法結(jié)合正則使用技巧,實例總結(jié)了replace方法配合正則表達(dá)式進(jìn)行變量、分組、字符等替換技巧,需要的朋友可以參考下2016-06-06

