1. 程式人生 > >基於vue-cli的vue專案之路由3--watch監聽路由

基於vue-cli的vue專案之路由3--watch監聽路由

有時候我們需要監聽路由,做出某種操作。。。程式碼主要在app.vue上

1.hello.vue頁面//獲取一個引數,第五行顯示
<template>
	<div class="hello">
		<!--{{ this.$route.params.num }}-->
		<h1>這個是hello頁面,穿過的引數是{{$route.params.hparam1}}</h1>
		<h2></h2>
	</div>
</template>
<script>
	export default {
		name: 'hello',
		data() {
			return {
				msg: 'this is the hello頁面'
			}
		},
		props: ['logo']
	}
</script>

2.foo.vue頁面//獲取兩個引數,第二十五,二十六行顯示引數
<template>
	<div class="hello">
		<h1>這個是foo頁面</h1>
		<h1>{{$route.params.fparam2}}</h1>
		<h1>{{$route.params.fparam1}}</h1>
		<h2></h2>
	</div>
</template>
<script>
	export default {
		name: 'hello',
		data() {
			return {
				msg: '這個是foo.vue頁面'
			}
		},
		props: ['logo']
	}
</script>

3.router/index.js路由配置檔案
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const router = new VueRouter({
	routes: [{
			name:"/hello",
			path: '/hello:hparam1',
			component: require('../components/Hello.vue')
		},
		{
			name: '/foo',
			path: '/foo/:fparam1/age:fparam2',
			component: require('../components/foo.vue')
		},
		{
			path: '*',
			redirect: '/hello:hparam1'
		},
	]
})
export default router;

4.App.vue主頁面//使用watch監聽
<template>
	<div id="app">
		<!-- <hello></hello> -->
		<div class="nav">
			<ul>
				<li>
					<router-link to="/hello123">hello頁面</router-link>
				</li>
				<li>
					<router-link to="/foo/mk/agehello">foo頁面</router-link>
				</li>
			</ul>
		</div>
		<div class="main">
			<router-view></router-view>
		</div>
	</div>
</template>
<script>
	export default {
		name: 'app',
		components: {},
		watch: {
			$route(to, from) {
				console.log(to);
				console.log(from);
			}
		}
	}
</script>
<style>
	body {background-color: #f8f8ff;font-family: 'Avenir', Helvetica, Arial, sans-serif;color: #2c3e50;}
	.nav {position: fixed;width: 108px;left: 40px;}
	.nav ul {list-style: none;margin: 0;padding: 0;}
	.nav ul li {width: 108px;height: 48px;line-height: 48px;border: 1px solid #dadada;text-align: center;	}
	.nav ul li a {display: block;position: relative;text-decoration: none;}
	.nav ul li img {position: absolute;	left: 0;top: 0;	width: 100px;height: 30px;}
	.main {	height: 400px;margin-left: 180px;margin-right: 25px;}
</style>

5.main.js//main配置路由的引用
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import VueRouter from 'vue-router'
import router from './router'
Vue.use(VueRouter);
new Vue({
	el: '#app',
	router,
	render: h => h(App)
})
效果是這樣的: