【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>
相关推荐
小徐_233314 分钟前
uni-app 组件库 Wot UI 2.0 发布了,我们带来了这些改变!
前端·微信小程序·uni-app
❀͜͡傀儡师19 分钟前
Claude Code 官方弃用 npm 安装方式:原因分析与完整迁移指南
前端·npm·node.js·claude code
知识分享小能手25 分钟前
ECharts入门学习教程,从入门到精通,ECharts高级功能(6)
前端·学习·echarts
阿祖zu25 分钟前
OpenClaw 入门到放弃:私人 AI 的初代原型机
前端·后端·aigc
ZC跨境爬虫25 分钟前
3D地球卫星轨道可视化平台开发 Day15(添加卫星系列模糊搜索功能)
前端·数据库·3d·交互·数据可视化
m0_7381207244 分钟前
渗透基础知识ctfshow——Web应用安全与防护(第六 七章)
服务器·前端·安全
Sun子矜44 分钟前
Web项目18+项目21
前端
踩着两条虫1 小时前
VTJ:项目模型架构
前端·低代码·ai编程
踩着两条虫1 小时前
VTJ:DSL语言规范
前端·低代码·ai编程
广州华水科技1 小时前
单北斗GNSS在水库形变监测中的应用与优势分析
前端