JS獲取地址欄參數(shù)的兩種方法(原生、vue)
若地址欄URL為:code-nav/article/917?type=12&title=abc,我們要獲取到地址欄后面的的type和title參數(shù),如何才能拿到呢?
解決方案:
1.原生JS實現(xiàn):
1.1 采用正則表達式獲取地址欄參數(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"); // 12
1.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; // abc
2.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)文章
JS基于對象的特性實現(xiàn)去除數(shù)組中重復項功能詳解
這篇文章主要介紹了JS基于對象的特性實現(xiàn)去除數(shù)組中重復項功能,結(jié)合實例形式較為詳細的分析了js基于key值唯一性實現(xiàn)數(shù)組去重的具體步驟與相關(guān)操作技巧,需要的朋友可以參考下2017-11-11javascript實現(xiàn)頁面刷新時自動清空表單并選中的方法
這篇文章主要介紹了javascript實現(xiàn)頁面刷新時自動清空表單并選中的方法,涉及javascript中reset與focus方法的相關(guān)使用技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-07-07javascript實現(xiàn)在指定元素中垂直水平居中
當談到網(wǎng)頁的布局中,居中問題一直得不到很有效的解決,居中通常是相對于某一個元素的,比如我們經(jīng)常所說的屏幕居中的問題,我們了解父元素的信息越多,我們就越能更加容易的實現(xiàn)居中布局。下面我們通過具體的實例來看看javascript如何來實現(xiàn)垂直水平居中2015-09-09