Vue的路由组件Router的基本使用

2024年05月22日 编程 暂无评论 阅读12 次

安装和注册

官方文档
https://router.vuejs.org/zh/introduction.html

npm i vue-router

"vue-router": "^4.3.0"

main.js中注册
import router from './router'

定义路由

import { createRouter, createWebHistory } from 'vue-router'  
import HomeView from '../components/HomeView.vue'  
import AboutView from '../components/AboutView.vue'  
  
const routes = [  
    {  
        path: '/',  
        name: 'Home',  
        component: HomeView  
    },  
    {  
        path: '/login',  
        name: 'login',  
        component: LoginView  
    },  
    {  
        path: '/more',  
        name: 'More',  
        component: ReSizeView  
    }  
]  
  
const router = createRouter({  
    history: createWebHistory(import.meta.env.BASE_URL),  
    routes  
})  
  
export default router

main.js中注册

import router from './router'
app.use(router)


//完整版
import { createApp } from 'vue'  
import ElementPlus from 'element-plus'  
import 'element-plus/dist/index.css'  
import App from './App.vue'  
import router from './router'  
import { createPinia } from 'pinia'  
const pinia = createPinia()  
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'  
pinia.use(piniaPluginPersistedstate)  
import "./tailwindcss.css"  
  
const app = createApp(App)  
app.use(ElementPlus)  
app.use(router)  
app.use(pinia)  
app.mount('#app')

在菜单中使用

<template>  
  <el-menu      :default-active="activeIndex"  
      class="el-menu-demo"  
      mode="horizontal"  
      :router="true"  
  >  
    <el-menu-item index="/">Home</el-menu-item>  
    <el-menu-item v-if="!isLoggedIn" index="/login">登录</el-menu-item>  
    <el-menu-item v-if="!isLoggedIn" index="/register">注册</el-menu-item>  
    <el-menu-item v-if="!isLoggedIn" index="/forgotPassword">忘记密码</el-menu-item>  
    <el-menu-item v-if="isLoggedIn" index="/userinfo">个人信息</el-menu-item>  
    <el-menu-item index="/about">About</el-menu-item>  
    <el-menu-item index="/testPinia">testPinia</el-menu-item>  
    <el-menu-item index="/more">In33fo</el-menu-item>  
  </el-menu>  
  <router-view/>
  </template>
//关键是<router-view/>

<script lang="ts" setup>  
import { ref, watch } from 'vue'  
import { useRoute } from 'vue-router'  
import { useUserStore } from '@/store/store.js';  
  
const activeIndex = ref('/')  
  
// 获取当前路由  
const route = useRoute()  
  
// 获取用户 storeconst userStore = useUserStore()  
  
// 计算是否已登录  
const isLoggedIn = ref(!!userStore.token)  
  
// 监听路由变化,更新activeIndex  
watch(route, (newRoute) => {  
  activeIndex.value = newRoute.path  
}, { immediate: true })  
  
// 监听 userStore.token 的变化  
watch(() => userStore.token, (newToken) => {  
  isLoggedIn.value = !!newToken  
})  
</script>

页面中主动调用

import { useRouter } from 'vue-router';  
const router = useRouter(); // 获取路由实例
router.push('/userinfo');
标签:

给我留言

切换注册

登录

忘记密码 ?

切换登录

注册