【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>
相关推荐
拉不动的猪4 分钟前
v2升级v3需要兼顾的几个方面
前端·javascript·面试
时光少年7 分钟前
Android 局域网NIO案例实践
android·前端
半兽先生22 分钟前
VueDOMPurifyHTML 防止 XSS(跨站脚本攻击) 风险
前端·xss
冴羽25 分钟前
SvelteKit 最新中文文档教程(20)—— 最佳实践之性能
前端·javascript·svelte
Nuyoah.26 分钟前
《Vue3学习手记2》
javascript·vue.js·学习
Jackson__32 分钟前
面试官:谈一下在 ts 中你对 any 和 unknow 的理解
前端·typescript
zpjing~.~40 分钟前
css 二维码始终显示在按钮的正下方,并且根据不同的屏幕分辨率自动调整位置
前端·javascript·html
红虾程序员1 小时前
Linux进阶命令
linux·服务器·前端
yinuo1 小时前
uniapp在微信小程序中实现 SSE 流式响应
前端
lynx_1 小时前
又一个跨端框架——万字长文解析 ReactLynx 实现原理
前端·javascript·前端框架