vue-router-路由
前言
项目地址:https://gitee.com/cnleika/vue-learning/tree/master/notebook/11-router
vue-router主要用于实现路径跳转,
我们在ssm和springboot中有用到过@RequestMapping("/路径")
,
vue-router的功能与此类似,用于映射组件的路径。
学习vue的时候最好还是从vue3以后开始学,很多语法都有变化,这部分内容debug了一个上午。
安装
在项目路径下使用
npm install vue-router
一个简单的demo
Main和Content组件
新建两个组件,Main.vue
和Content.vue
Main.vue
<script setup>
</script>
<template>
<h1>main</h1>
</template>
<style scoped>
</style>
Content.vue
<script setup>
</script>
<template>
<h1>内容页</h1>
</template>
<style scoped>
</style>
script setup语法糖
只需要在script标签中添加setup,组件只需引入不用注册,属性和方法也不用返回,setup函数也不需要,甚至export default都不用写了,
不仅是数据,计算属性和方法,甚至是自定义指令也可以在我们的template中自动获得。
style scope
指明css只在当前模板内生效
配置路由index.js
在src/router目录下新建index.js,用于配置路由
import {createRouter, createWebHashHistory} from "vue-router";
// @这东西代表着到src这个文件夹的路径
// 1. 引入组件
const Content = () => import("@/components/Content.vue")
const Main = () => import("@/components/Main.vue")
// 2. 配置导出路由
const routes = [
{
// run to Content.vue
name: 'content',
// 路由路径
path: '/content',
// 跳转组件
component: Content
},
{
// run to Main.vue
name: 'main',
// 路由路径
path: '/main',
// 跳转组件
component: Main
}
];
// 3. 生成路由
const router = createRouter({
history: createWebHashHistory(),
routes: routes
});
// 4. 导出路由
export default router;
挂载路由main.js
import {createApp} from 'vue'
import App from '@/App.vue'
import '@/assets/main.css'
// 自动扫描里面的router配置,重要!!!
import router from '@/router'
const app = createApp(App)
app.use(router)// vue3挂载路由,一定要放在mount挂载前!
app.mount('#app')
App.vue
<script setup>
</script>
<template>
<div id="app">
<h1>Hello</h1>
<router-link to="/main">首页</router-link>
<router-link to="/content">内容页</router-link>
<router-view></router-view>
</div>
</template>
<style scoped>
/*scoped 作用域,指css只在当前模板生效,推荐添加*/
</style>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!