创建工程

Vue Router

一、声明式路由

1.创建Vue工程

打开终端 输入```npm creat vite````

2.更新依赖

  • 在终端,输入cd ./miniheadlin-router进入目录下
  • 输入npm install更新依赖

3.安装路由

  • 在终端输入npm install vue-router

4.路由配置

在 src 下创建 routers 文件夹,并新建 router.js:

import Home from '../components/Home.vue'
import List from '../components/List.vue'
import Add from '../components/Add.vue'

const routes = [
  { path: '/', redirect: '/home' },
  { path: '/home', component: Home },
  { path: '/list', component: List },
  { path: '/add', component: Add },
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

export default router

5.准备页面组件

在 components/ 下创建:

Home.vue

</script>

<template>
  <div>
    <h1>Home页面</h1>
  </div>
</template>

<style scoped>
</style>

List.vue

</script>

<template>
    <div>
        <h1>List页面</h1>
    </div>
</template>

<style scoped>
</style>

Add.vue

</script>

<template>
    <div>
        <h1>Add页面</h1>
    </div>
</template>

<style scoped>
</style>

二、编程式路由

通过 useRouter动态控制页面跳转
示例:

import { useRouter } from 'vue-router';

let router = useRouter();

let myAdd = () => {
  router.push('/add');
}
</script>

<template>
  <button @click="myAdd()">Add</button>
</template>

三、路由守卫

1.全局前置守卫

  console.log(to.path, from.path)

  if (to.path == '/index') {
    next()
  } else {
    next('/index')
  }
})

2.全局后置守卫

  console.log(`Navigate from ${from.path} to ${to.path}`);
});

在Router基础上添加Pinia

创建工程

在router的基础上 继续在终端输入npm install pinia

posted @ 2026-06-15 08:55  碎碎草莓酪123  阅读(11)  评论(0)    收藏  举报