vue3配置router路由并實現(xiàn)頁面跳轉(zhuǎn)功能
1、安裝vue-router
用vue3需要安裝版本4.0以上的vue-router,安裝命令:
npm install vue-router@next --save
vue2盡量安裝4.0以下版本,安裝命令:
npm i vue-router@3.1.3
在package.json中可以查看vue-router版本號:
2、根目錄下新建router文件夾,下面新建index.js文件和routes.js
2.1文件中引入vue方法、配置頁面具體路徑
vue2和vue3代碼區(qū)別如下:
【vue3】
ps:引入文件時記得新建view文件夾以及里面的A、B.vue兩個頁面
【vue2】
3、main.js文件中引入路由
4、APP.vue里聲明路由的占位符<router-view></router-view>
5、測試
6、文件代碼
HelloWorld.vue
<template> <!-- <h1>{{ msg }}</h1> --> <div class="card"> <router-link to="/A">A</router-link> <router-link to="/B">B</router-link> <!-- 第二種方法 router.push--> <!-- <button @click="show('a')">A頁面</button> <button @click="show('b')">B頁面</button> --> </div> </template> <script setup> import {useRouter,useRoute} from 'vue-router' //const router = useRouter() //const route = useRoute() // defineProps({ // msg: String, // }) // 第二種跳轉(zhuǎn)方法 // const show=(index)=> { // if(index == 'a') { // router.push('/a') // } // if(index == 'b') { // router.push('/b') // } // } </script> <style scoped></style>
index.js
import {createRouter, createWebHashHistory,createWebHistory} from 'vue-router' import routes from './routes' const router = createRouter({ routes, history: createWebHashHistory() }) export default router
routes.js
const a = () => import('../view/A.vue') const b = () => import('../view/B.vue') const routes = [ //實現(xiàn)路由重定向,當(dāng)進(jìn)入網(wǎng)頁時,路由自動跳轉(zhuǎn)到/a路由 //{ // path:'/', // redirect:'/a' // }, { path: '/', component:a, }, { name: 'a', path: '/a', component:a }, { name: 'b', path: '/b', component: b }, ]; export default routes
APP.vue
<script setup> import HelloWorld from './components/HelloWorld.vue' </script> <template> <div> <h1>App 組件</h1> <HelloWorld msg="hello" /> <!-- 聲明路由的占位符 --> <router-view></router-view> </div> </template> <style scoped> </style>
補充:
編程式導(dǎo)航
通過調(diào)用 API 實現(xiàn)導(dǎo)航的方式,叫做編程式導(dǎo)航。
與之對應(yīng)的,通過點擊鏈接實現(xiàn)導(dǎo)航的方式,叫做聲明式導(dǎo)航。例如:
1. 普通網(wǎng)頁中點擊 鏈接、vue 項目中點擊 都屬于聲明式導(dǎo)航
2. 普通網(wǎng)頁中調(diào)用 location.href 跳轉(zhuǎn)到新頁面的方式,屬于編程式導(dǎo)航
vue-router 中的編程式導(dǎo)航 API
vue-router 提供了許多編程式導(dǎo)航的 API,其中最常用的兩個 API 分別是:
this.$router.push('hash 地址') 跳轉(zhuǎn)到指定 Hash 地址,從而展示對應(yīng)的組件 this.$router.go(數(shù)值 n) 實現(xiàn)導(dǎo)航歷史的前進(jìn)、后退
history.go(-2);//后退兩次 history.go(2);//前進(jìn)兩次 history.back(); //后退 hsitory.forward(); //前進(jìn)
但是history也是有缺點的,不怕前進(jìn)后退跳轉(zhuǎn),就怕刷新(如果后端沒有準(zhǔn)備的話),因為刷新是實實在在地去請求服務(wù)器了。
到此這篇關(guān)于vue3配置router路由并實現(xiàn)頁面跳轉(zhuǎn)的文章就介紹到這了,更多相關(guān)vue3頁面跳轉(zhuǎn)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
el-tree的實現(xiàn)葉子節(jié)點單選的示例代碼
本文主要介紹了el-tree的實現(xiàn)葉子節(jié)點單選的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08vue3使用element-plus中el-table組件報錯關(guān)鍵字'emitsOptions'與&
這篇文章主要給大家介紹了關(guān)于vue3使用element-plus中el-table組件報錯關(guān)鍵字'emitsOptions'與'insertBefore'的相關(guān)資料,文中將解決方法介紹的非常詳細(xì),需要的朋友可以參考下2022-10-10