【vue】--vue-router使用

安装

npm create vue@latest

创建文件

--src

---routers

---index.ts

配置

src->routers->index.ts

ts 复制代码
import { createWebHashHistory, createRouter } from 'vue-router';

import TabsView from '@/view/tabs/TabsView.vue';
import HomeView from '@/view/tabs/Home/HomeView.vue';
import MeView from '@/view/tabs/Me/MeView.vue';
import OrderView from '@/view/tabs/Order/OrderView.vue';

const routes = [
  {
    path:'/',
    //重定向路径,首次进入页面的路径
    redirect:'/home'
  },
  { path: '/tabs', 
    name: 'TabsView',
    component: TabsView,
    //子路由
    children:[
      { path: '/home', name: 'HomeView', component: HomeView },
      { path: '/me', name: 'MeView', component: MeView },
      { path: '/order', name: 'OrderView', component: OrderView },
    ]
  }
]
const router = createRouter({
  history: createWebHashHistory(),
  routes,
})

export default router

App.vue

vue 复制代码
<script setup lang="ts">
</script>

<template>
  <RouterView></RouterView> //添加路由
</template>

<style scoped></style>

main.ts

ts 复制代码
import App from "./App.vue";
import router from "@/routers"; //引入路由

createApp(App).use(router).mount("#app");
 

页面中使用路由跳转

不使用组件

vue 复制代码
<script setup lang='ts'>
//引入
import { useRoute } from 'vue-router';
import { ref } from 'vue';
//使用
const route = useRoute(); 
</script>
<template>
    <div>
            <button @click="active = 'home'" >home</button>
            <button @click="active = 'order'" >order</button>
            <button @click="active = 'me'" >me</button>
    </Button>
</template>
<style scoped>
</style>

使用组件

vue 复制代码
<script setup lang='ts'>
//使用了vant组件
import { Tabbar, TabbarItem } from 'vant';
import { useRoute, useRouter } from 'vue-router';
import { ref, watch } from 'vue';

const route = useRoute();
const router = useRouter();

const active = ref(route.name as string);

//监听点击的事件
watch(active, (nv) => {
    router.push({ name: nv });
});


</script>
<template>
    <div>
        <div class="center">{{ active }}</div>
        <Tabbar v-model="active">
            <TabbarItem name="HomeView" icon="home-o">首页</TabbarItem>
            <TabbarItem name="OrderView" icon="bars">订单</TabbarItem>
            <TabbarItem name="MeView" icon="contact">我的</TabbarItem>
        </Tabbar>
    </div>

</template>
<style scoped>
.center {
    text-align: center;
}
</style>
相关推荐
gnip1 分钟前
项目开发流程之技术调用流程
前端·javascript
转转技术团队15 分钟前
多代理混战?用 PAC(Proxy Auto-Config) 优雅切换代理场景
前端·后端·面试
南囝coding16 分钟前
这几个 Vibe Coding 经验,真的建议学!
前端·后端
gnip30 分钟前
SSE技术介绍
前端·javascript
yinke小琪44 分钟前
JavaScript DOM节点操作(增删改)常用方法
前端·javascript
枣把儿1 小时前
Vercel 收购 NuxtLabs!Nuxt UI Pro 即将免费!
前端·vue.js·nuxt.js
望获linux1 小时前
【Linux基础知识系列】第四十三篇 - 基础正则表达式与 grep/sed
linux·运维·服务器·开发语言·前端·操作系统·嵌入式软件
爱编程的喵1 小时前
从XMLHttpRequest到Fetch:前端异步请求的演进之路
前端·javascript
喜欢吃豆1 小时前
深入企业内部的MCP知识(三):FastMCP工具转换(Tool Transformation)全解析:从适配到增强的工具进化指南
java·前端·人工智能·大模型·github·mcp
豆苗学前端1 小时前
手把手实现支持百万级数据量、高可用和可扩展性的穿梭框组件
前端·javascript·面试