淺談vue-router 路由傳參的方法
更新時間:2017年12月27日 10:02:14 作者:Ecl_02b8
這篇文章主要介紹了淺談vue-router 路由傳參的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
路由傳參數(shù)。在很多時候我們需要路由上面?zhèn)鬟f參數(shù),比如新聞列表頁,我們需要傳遞新聞ID,給新聞詳細頁。
1.新聞列表頁模板
<template id="news">
<div>
<h2>新聞列表</h2>
<ul>
<li>
<router-link to="/news/001">新聞001</router-link>
</li>
<li>
<router-link to="/news/002">新聞002</router-link>
</li>
</ul>
</div>
</template>
我們訪問/news/001,跳轉(zhuǎn)到新聞詳細頁,展示001的這條新聞。
2.新聞詳細頁組件準備
<template id="NewsDetail">
<div>
新聞詳細頁面
<span>{{$route.params.id}}</span>
</div>
</template>
$route.params.id獲取路由上的參數(shù)
3.定義路由,增加一個路由
{ path: '/news/:id', component: NewsDetail },
4.全部代碼如下:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8">
<script src="http://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</head>
<body>
<div id="box">
<p>
<router-link to="/home">home</router-link>
<router-link to="/news">news</router-link>
</p>
<router-view></router-view>
</div>
<!-- 模板抽離出來 -->
<template id="home">
<!-- 注意:組件只能有一個根元素,所以我們包裝到這個div中 -->
<div>
<h2>首頁</h2>
<router-link to="/home/login">登錄</router-link>
<router-link to="/home/reg">注冊</router-link>
<!-- 路由匹配到的組件將渲染在這里 -->
<router-view></router-view>
</div>
</template>
<template id="news">
<div>
<h2>新聞列表</h2>
<ul>
<li>
<router-link to="/news/001">新聞001</router-link>
</li>
<li>
<router-link to="/news/002">新聞002</router-link>
</li>
</ul>
</div>
</template>
<template id="login">
<div>登錄界面</div>
</template>
<template id="reg">
<div>注冊界面</div>
</template>
<template id="NewsDetail">
<div>
新聞詳細頁面
<span>{{$route.params.id}}</span>
</div>
</template>
<script type="text/javascript">
// 1. 定義(路由)組件。
const Home = { template: '#home' };
const News = { template: '#news' };
const Login = { template: '#login' };
const Reg = { template: '#reg' };
//新聞詳細頁組件
const NewsDetail = { template: '#NewsDetail' };
// 2. 定義路由
const routes = [
{ path: '/', redirect: '/home' },
{
path: '/home',
component: Home,
children:[
{ path: '/home/login', component: Login},
{ path: '/home/reg', component: Reg}
]
},
{ path: '/news', component: News,},
{ path: '/news/:id', component: NewsDetail },
]
// 3. 創(chuàng)建 router 實例,然后傳 `routes` 配置
const router = new VueRouter({
routes // (縮寫)相當于 routes: routes
})
// 4. 創(chuàng)建和掛載根實例。
// 記得要通過 router 配置參數(shù)注入路由,
// 從而讓整個應用都有路由功能
const app = new Vue({
router
}).$mount('#box')
// 現(xiàn)在,應用已經(jīng)啟動了!
</script>
</body>
</html>
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
詳解.vue文件中監(jiān)聽input輸入事件(oninput)
本篇文章主要介紹了詳解.vue文件中監(jiān)聽input輸入事件(oninput),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-09-09
vuex刷新之后數(shù)據(jù)丟失,數(shù)據(jù)持久化,vuex-persistedstate問題
這篇文章主要介紹了vuex刷新之后數(shù)據(jù)丟失,數(shù)據(jù)持久化,vuex-persistedstate問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03
Vue 使用v-model實現(xiàn)控制子組件顯隱效果
v-model 可以實現(xiàn)雙向綁定的效果,允許父組件控制子組件的顯示/隱藏,同時允許子組件自己控制自身的顯示/隱藏,本文給大介紹Vue 使用v-model實現(xiàn)控制子組件顯隱,感興趣的朋友一起看看吧2023-11-11

