1. 程式人生 > >Vue.js框架--路由程式設計式的導航 和History 模式(十九)

Vue.js框架--路由程式設計式的導航 和History 模式(十九)

主要操作技能:

一、程式設計式的導航        除了使用 <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中常用的路由模式

hash(#):預設路由模式      —— 使用 URL 的 hash 來模擬一個完整的 URL,於是當 URL 改變時,頁面不會重新載入。 histroy(/)切換路由模式      —— 這種模式充分利用 history.pushState API 來完成 URL 跳轉而無須重新載入頁面      hash路由模式(預設)  ==> http://localhost:8080/#/detail/495  const router = new VueRouter({   routes  })      history路由模式  ==>   http://localhost:8080/detail/495   const router = new VueRouter({   mode: 'history',   //history模式   routes })

編寫程式碼:

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'})