【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>
相关推荐
三十_A1 小时前
如何正确实现圆角渐变边框?为什么 border-radius 对 border-image 不生效?
前端·css·css3
小满zs1 小时前
Next.js第十三章(缓存组件)
前端
前端老宋Running1 小时前
“受控组件”的诅咒:为什么你需要 React Hook Form + Zod 来拯救你的键盘?
前端·javascript·react.js
风止何安啊1 小时前
拿捏 React 组件通讯:从父子到跨组件的「传功秘籍」
前端·react.js·面试
懒得不想起名字2 小时前
将flutter打成aar包嵌入到安卓
前端
Highcharts.js2 小时前
官方文档|Angular 框架集成 Highcharts Dashboards
前端·javascript·angular.js·highcharts·看板·使用文档·dashboards
韭菜炒大葱2 小时前
React 新手村通关指南:状态、组件与魔法 UI 🧙‍♂️
前端·javascript·react.js
Dwzun2 小时前
基于SpringBoot+Vue的二手书籍交易平台系统【附源码+文档+部署视频+讲解)
java·vue.js·spring boot·后端·spring·计算机毕业设计
天天扭码2 小时前
深入MCP本质——编写自定义MCP Server并通过Cursor调用
前端·mcp
北辰alk3 小时前
Vue3 事件修饰符深度解析:从基础到高级应用的完整指南
vue.js