Vue-router參數傳遞
為什么要在router中傳遞參數
設想一個場景,當前在主頁中,你需要點擊某一項查看該項的詳細信息。那么此時就需要在主頁傳遞該項的id到詳情頁,詳情頁通過id獲取到詳細信息。
vue-router 參數傳遞的方式
Parma傳參
貼代碼:
/router/index.vue
export default new Router({ routes: [ { path: '/', name: 'Home', component: Home }, { path: '/work', name: 'Work', component: Work } ] })組件Works傳遞一個work的id到組件Work
/components/Home/Comtent/Works.vue
// 觸發它傳遞一個對象到組件WorkgetIt (id) { this.$router.push({ path: '/work', name: 'Work', params: { id: id } }) }/components/Work/Index.vue
<template> <div class="work"> work: {{id}} </div> </template> <script> export default { name: 'Work', data () { return { id: this.$route.params.id //拿到id } } } </script>運行截圖:


query傳參
將上面的parmas改為query即可,即:
// 傳入 this.$router.push({path: '/work',name: 'Work',query: { id: id} }) ... ... this.$route.query.id // 獲取parmas與query的區別
query是通過url傳遞參數,始終顯示在url中
parmas傳參,刷新頁面過后就沒有數據了,無法將獲取到的參數進行保存
總結: 這兩種參數的傳遞方式,各有各的用途,具體的還要自己親手試一試才知道,前端這個領域,還是要多多親自動手實踐。
新聞熱點
疑難解答