Vue Router 是 Vue.js 官方的路由管理库,用于构建单页面应用(SPA)的路由系统。它能够将不同的页面映射到对应的组件,实现页面之间的切换和导航。Vue Router 提供了丰富的功能,包括路由参数、嵌套路由、导航守卫等,使得构建复杂的前端应用变得更加容易和高效。
主要特性:
路由映射: 将不同的 URL 映射到对应的 Vue 组件,实现页面的模块化和组件化。
嵌套路由: 支持在组件内部定义子路由,形成嵌套的路由结构,使页面的层级结构更加清晰。
路由参数: 可以通过路由参数传递数据,动态地改变页面的内容。
导航守卫: 提供全局的导航守卫,允许在导航过程中进行一些操作,如权限控制、页面跳转前的确认等。
路由懒加载: 支持将路由按需加载,减小初始页面加载的体积,提升应用性能。
安装Vue
npm install vue-router
项目中使用 Vue 的示例代码
在 src 目录下,App.vue 是项目的根组件,以下是一个简单的 App.vue 示例,展示了如何在项目中使用 Vue 来实现一个简单的计数器功能:
<template>
<div id="app">
<h1>{
{ message }}</h1>
<p>当前计数: {
{ count }}</p>
<button @click="increment">增加计数</button>
</div>
</template>
<script setup>
import { ref } from 'vue';
// 定义响应式数据
const message = ref('欢迎使用 Vue 项目');
const count = ref(0);
// 定义方法
const increment = () => {
count.value++;
};
</script>
<style scoped>
/* 样式 */
#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;
}
button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
</style>
Vue 在组件中使用的例子
创建组件
在 src/components 目录下创建一个新的组件文件 MyComponent.vue,以下是该组件的代码:
<template>
<div>
<h2>{
{ componentMessage }}</h2>
<p>当前组件计数: {
{ componentCount }}</p>
<button @click="incrementComponentCount">增加组件计数</button>
</div>
</template>
<script setup>
import { ref } from 'vue';
// 定义组件内的响应式数据
const componentMessage = ref('这是一个 Vue 组件');
const componentCount = ref(0);
// 定义组件内的方法
const incrementComponentCount = () => {
componentCount.value++;
};
</script>
<style scoped>
/* 组件样式 */
div {
border: 1px solid #ccc;
padding: 20px;
margin: 20px;
}
button {
margin-top: 10px;
}
</style>