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.vueContent.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>

效果图

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

虚拟内存会梦见进程调度嘛?

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值