Vue.js框架--路由程式設計式的導航 和History 模式(十九)
阿新 • • 發佈:2018-12-10
主要操作技能:
一、程式設計式的導航 除了使用 <router-link> 建立 a 標籤來定義導航連結, 我們還可以藉助 router 的例項方法,通過編寫程式碼來實現
點選 <router-link :to="..."> 等同於呼叫 router.push(...)。 //定義導航連結 <router-link to="/news">新聞</router-link> //(1) news 跳轉到新聞 this.$router.push({path:'news'}); //detail/495 跳轉到新聞詳情 this.$router.push({path:'/detail/495'}); //(2) 命名的路由 this.$router.push({name:'news'}) { path: '/news', name:'news', //指定名稱哦! component: News } 二、vue中常用的路由模式
編寫程式碼:
Home.vue
<template> <!--所以的內容多要被根節點包含起來 --> <div id="home"> <h2>首頁元件 <button @click="goNews()">通過js跳轉到新聞頁面</button> </h2> </div> </template> <script> export default { data() { //資料 return { msg: 'I am home component!', list: ['product1', 'product2', 'product3'] } }, methods:{ goNews(){ //點選 <router-link :to="..."> 等同於呼叫 router.push(...)。 //注意:在 Vue 例項內部,你可以通過 $router 訪問路由例項。因此你可以呼叫 this.$router.push。 //第一種跳轉方式 //news 跳轉到新聞 // this.$router.push({path:'news'}); //detail/495 跳轉到新聞詳情 // this.$router.push({path:'/detail/495'}); //第二種跳轉方式 // 命名的路由 this.$router.push({name:'news'}) } } } </script>
效果:
(1) this.$router.push({path:'news'});
(2) this.$router.push({path:'/detail/495'});
(3) this.$router.push({name:'news'})