Vue:vue-router使用指南

一、简介

点击查看vue-router官网

Vue Router 是 Vue.js 的官方路由。它与 Vue.js 核心深度集成,让用 Vue.js 构建单页应用变得轻而易举。功能包括:

  • 嵌套路由映射
  • 动态路由选择
  • 模块化、基于组件的路由配置-
  • 路由参数、查询、通配符-
  • 展示由 Vue.js 的过渡系统提供的过渡效果-
  • 细致的导航控制-
  • 自动激活 CSS 类的链接-
  • HTML5 history 模式或 hash 模式-
  • 可定制的滚动行为-
  • URL 的正确编码

二、安装

2.1 包管理器

对于一个现有的使用 JavaScript 包管理器的项目,你可以从 npm registry 中安装 Vue Router:

npm install vue-router@4

//vue2 安装对应的版本vue-router@3,例如指定版本:3.6.5
npm install vue-router@3.6.5

如果你打算启动一个新项目,你可能会发现使用 create-vue 这个脚手架工具更容易,它能创建一个基于 Vite 的项目,并包含加入 Vue Router 的选项:

npm create vue@latest

你需要回答一些关于你想创建的项目类型的问题。如果您选择安装 Vue Router,示例应用还将演示 Vue Router 的一些核心特性。

使用包管理器的项目通常会使用 ES 模块来访问 Vue Router,例如 import { createRouter } from ‘vue-router’。

三、实例演示

Vue Router 是 Vue 官方的客户端路由解决方案。

客户端路由的作用是在单页应用 (SPA) 中将浏览器的 URL 和用户看到的内容绑定起来。当用户在应用中浏览不同页面时,URL 会随之更新,但页面不需要从服务器重新加载。

Vue Router 基于 Vue 的组件系统构建,你可以通过配置路由来告诉 Vue Router 为每个 URL 路径显示哪些组件。

提醒:下面实例是在TestVue2的项目里运行的

3.1 TestVue2项目结构图

在这里插入图片描述

3.2 安装 vue-router@3.6.5
npm install vue-router@3.6.5

安装成功后,查看package.json文件
在这里插入图片描述

3.3 创建路由器实例
  1. 在src目录里创建views文件夹,在里面分别创建teststore1.vue和teststore2.vue文件

  2. 在src目录里创建router文件夹,在里面创建index.js文件

router文件夹里index.js文件代码

import Vue from 'vue'
import Router from 'vue-router'
import TestStore1 from '../views/teststore1.vue'
Vue.use(Router)
export default new Router({
	mode:'history',
	// base: 'http://192.168.0.102:8080/',
	// 下面第一个 path:'/', 解决默认进入的官方首页问题
	routes:[
		{
			name:'首页',
			path:'/',
			component: () => import ("../views/home.vue")
		},
		{
			name:'状态管理1',
			path:'/teststore1',
			component: TestStore1,
			meta:{
				title:'store1'
			}
		},
		{
			name:'状态管理2',
			path:'/teststore2',
			component: () => import("../views/teststore2.vue")
		},
	]
})

teststore1.vue代码

<template>
	<div>
		<!-- <h1>store 1 数量:{{this.$store.state.count}}</h1> -->
		<!-- <h1>getComputedCount 数量:{{getComputedCount}}</h1> -->
		<!-- <h1>mapState 数量:{{count}}</h1>
		<button @click="increment">+</button>
		<button @click="decrement">-</button>
		</br>
		<button @click="doactions">点击两秒后数量自动加1</button>
		<br />
		<br />
		<p>
			<button v-on:click="getCount">获取localCount最新值</button>
			获取到的数量:{{localCount}}
		</p>
		<br />
		<br /> -->
		<button @click="openTest2Page">打开test2页面</button>

	</div>
</template>

<script>
	// import {
	// 	mapState
	// } from 'vuex'
	export default {
		name: 'teststore1',
		data() {
			return {
				localCount: 0,
			}
		},
		// computed: {
		// 	...mapState([
		// 		'count',
		// 	]), //推荐这种方式
		// },
		
		// watch: {
		// 	count: {
		// 		handler(newVal, oldVal) {
		// 			console.log(`teststore1 watch 新的值: ${newVal} , 旧的值: ${oldVal}`)
		// 		},
		
		// 	}
		// },
		
		created() {
			console.log("teststore1 执行了 created ")
		},
		
		activated() {
			console.log("teststore1 执行了 activated ")
		},
		
		mounted() {
			// console.log("teststore1 执行了 mounted ", this.$store)
		},
		
		beforeUpdate() {
			console.log("teststore1 执行了 beforeUpdate ")
		},
		
		updated() {
			console.log("teststore1 执行了 updated ")
		},
		
		beforeDestroy() {
			console.log("teststore1 执行了 beforeDestroy ")
		},
		
		destroyed() {
			console.log("teststore1 执行了 beforeDestroy ")
		},
		
		methods: {
			// increment() {
			// 	this.$store.commit('increment')
			// },

			// decrement() {
			// 	this.$store.commit('decrement')
			// },
			// // // 异步任务 store.dispatch	
			// doactions() {
			// 	this.$store.dispatch('tryactions', 2000)
			// },

			// getCount() {
			// 	this.localCount = this.$store.state.count
			// 	console.log("执行了 getCount this.localCount = ", this.localCount)
			// },
			
			openTest2Page(){
				this.$router.push('/teststore2')
			},
		}

	}
</script>

<style>
	button {
		margin-left: 1.25rem;
		margin-top: 1.0rem;
	}
</style>

teststore2.vue代码

<template>
	<div>
		<!-- <h1>store 2 数量:{{this.$store.state.count}}</h1> -->
		<!-- <h1>store 2 数量:{{count}}</h1>
		<button @click="increment">+</button>
		<button @click="decrement">-</button> -->
		<button @click="goBack">返回到上个页面</button>

	</div>
</template>

<script>
	// import {
	// 	mapState
	// } from 'vuex'
	export default {
		name: 'teststore2',
		data() {
			return {
				mCount: 0,
			}
		},
		
		created() {
			console.log("teststore2 执行了 created ")
		},
		
		activated() {
			console.log("teststore2 执行了 activated ")
		},
		
		mounted() {
			console.log("teststore2 执行了 mounted ", this.$store)
		},
		
		beforeUpdate() {
			console.log("teststore2 执行了 beforeUpdate ")
		},
		
		updated() {
			console.log("teststore2 执行了 updated ")
		},
		
		beforeDestroy() {
			console.log("teststore2 执行了 beforeDestroy ")
		},
		
		destroyed() {
			console.log("teststore2 执行了 beforeDestroy ")
		},
		
		// computed: {
		// 	...mapState([
		// 		'count',
		// 	]),
		// },

		mounted() {
			// console.log("teststore2 执行了 mounted ",this.$store)
		},
		methods: {
			// increment() {
			// 	this.$store.commit('increment')
			// },

			// decrement() {
			// 	this.$store.commit('decrement')
			// },
			
			goBack(){
				this.$router.replace('/teststore1')
			}
		}

	}
</script>

<style>
	button {
		margin-left: 1.25rem;
	}
</style>

四、注册路由器插件

在router文件里index.js里使用了Vue.use(Router),接下来在main.js将index.js导入, 将其注册为插件

main.js文件代码

import Vue from 'vue'
import App from './App.vue'
// 将 Vuex Store 注入到应用中
//import store from './store'
import router from './router'
Vue.config.productionTip = false
// Vue.prototype.$store = store

// https://www.jb51.net/javascript/297247rzd.htm
// 如果使用 ES6,你也可以以 ES6 对象的 property 简写 (用在对象某个 property 的 key 和被传入的变量同名时):
new Vue({
	router,
	render: h => h(App),
}).$mount('#app')

// 使用 ES2015 语法
// new Vue({
// 	router: router,
// 	store: store,
// 	render: h => h(App),
// }).$mount('#app')

等价于

const app = createApp(App)
app.use(router)
app.mount('#app')

和大多数的 Vue 插件一样,use() 需要在 mount() 之前调用。

如果你好奇这个插件做了什么,它的职责包括:

  • 全局注册 RouterView 和 RouterLink 组件。
  • 添加全局 $router 和 $route 属性。
  • 启用 useRouter() 和 useRoute() 组合式函数。
  • 触发路由器解析初始路由。

五、App.vue里使用router-view

App.vue文件代码

<template>
  <div id="app">
	  <!-- 重要的步骤 -->
	  <router-view />
    <!-- <img alt="Vue logo" src="./assets/logo.png"> -->
    <!-- <HelloWorld msg="Welcome to Your Vue.js App"/> -->
	<!-- <router-link to="/teststore1">teststore1</router-link> -->
	<!-- <div @click="test">点击跳转</div> -->
  </div>
</template>

<script>
// import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'app',
  // components: {
  //   HelloWorld
  // },
  methods: {
  	test(){
		console.log("执行了 test")
		this.$router.push('/teststore1')
	}
  },
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

六、访问路由器和当前路由

你很可能想要在应用的其他地方访问路由器。

如果你是从 ES 模块导出路由器实例的,你可以将路由器实例直接导入到你需要它的地方。在一些情况下这是最好的方法,但如果我们在组件内部,那么我们还有其他选择。

在组件模板中,路由器实例将被暴露为$router。这与同样被暴露的 $route 一样,但注意前者最后有一个额外的 r。

如果我们使用选项式 API,我们可以在 JavaScript 中如下访问这两个属性:this.$router 和 this.$route。在演练场示例中的 home.vue 组件中,路由器就是这样获取的。

home.vue代码

<template>

	<div>
		<h1>首页</h1>
		<router-link to="/teststore1">打开teststore1</router-link>
		<br />
		<button @click="test">打开teststore2页面</button>
	</div>
</template>

<script>
	export default {
		methods: {
			test() {
				this.$router.push('/teststore2')
			}
		},
	}
</script>

<style>

</style>

这里调用了 push(),这是用于编程式导航的方法

七、启动TestVue2项目

在终端里输入下面命令:
提醒:因为电脑里node版本问题,前面加了NODE_OPTIONS=–openssl-legacy-provider

NODE_OPTIONS=--openssl-legacy-provider npm run serve

在这里插入图片描述

八、效果图

home.vue页面
在这里插入图片描述

teststore1.vue页面
在这里插入图片描述

teststore2.vue页面
在这里插入图片描述

九、TestVue2项目源码

点击查看TestVue2源码

  • 31
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值