【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>
相关推荐
二哈喇子!1 小时前
BOM模型
开发语言·前端·javascript·bom
二哈喇子!1 小时前
Vue2 监听器 watcher
前端·javascript·vue.js
yanyu-yaya2 小时前
前端面试题
前端·面试·前端框架
二哈喇子!2 小时前
使用NVM下载Node.js管理多版本
前端·npm·node.js
GGGG寄了3 小时前
HTML——文本标签
开发语言·前端·html
2501_944521593 小时前
Flutter for OpenHarmony 微动漫App实战:推荐动漫实现
android·开发语言·前端·javascript·flutter·ecmascript
Amumu121384 小时前
Vue核心(三)
前端·javascript·vue.js
CoCo的编程之路4 小时前
2026 前端效能革命:如何利用智能助手实现“光速”页面构建?深度横评
前端·人工智能·ai编程·comate·智能编程助手·文心快码baiducomate
RFCEO4 小时前
HTML编程 课程五、:HTML5 新增语义化标签
前端·html·html5·跨平台·语义化标签·可生成安卓/ios·html最新版本
2501_944521595 小时前
Flutter for OpenHarmony 微动漫App实战:图片加载实现
android·开发语言·前端·javascript·flutter·php