1. 程式人生 > 其它 >VUE路由基本操作

VUE路由基本操作

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>vue路由</title>
		<script src="vue.min.js"></script>
		<script src="vue-router.min.js"></script>
	</head>
	<body>
		<div id="app">
			<!-- 使用 router-link 元件來導航. -->
			<!-- 通過傳入 `to` 屬性指定連結. -->
			<!-- <router-link> 預設會被渲染成一個 `<a>` 標籤 -->
			<router-link to="/">one</router-link>
			<router-link to="/two">two</router-link>
			<router-link to="/three">three</router-link>
			<!-- 一定要定義路由的出口 -->
			<router-view></router-view>
		</div>
		<script>
			// 1. 定義(路由)元件。
			// 可以從其他檔案 import 進來
			const T1 = {
				template: '<div>one</div>'
			}
			const T2 = {
				template: '<div>two</div>'
			}
			const T3 = {
				template: '<div>three</div>'
			}
			// 2. 定義路由
			// 每個路由應該對映一個元件。
			const routes = [{
				path: '/',
				redirect: '/one'
			}, {
				path: '/one',
				component: T1
			}, {
				path: '/two',
				component: T2
			}, {
				path: '/three',
				component: T3
			}]
			// 3. 建立 router 例項,然後傳 `routes` 配置
			const router = new VueRouter({
				routes
			})
			// 4. 建立和掛載根例項。
			// 從而讓整個應用都有路由功能
			const app = new Vue({
				el: '#app',
				router
			})
		</script>
	</body>
</html>