最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

vue-router路由配置實(shí)踐

 更新時(shí)間:2025年10月22日 09:05:50   作者:花開莫與流年錯(cuò)_  
本文介紹了Vue路由的配置方法,包括基礎(chǔ)路由、嵌套路由、動(dòng)態(tài)路由的添加與刪除,以及如何通過router-link跳轉(zhuǎn)、push和replace方法導(dǎo)航,還講解了動(dòng)態(tài)路由在登錄場(chǎng)景下的應(yīng)用及路由守衛(wèi)的使用

路由配置主要是用來確定網(wǎng)站訪問路徑對(duì)應(yīng)哪個(gè)文件代碼顯示的,這里主要描述路由的配置、子路由、動(dòng)態(tài)路由(運(yùn)行中添加刪除路由)

1、npm添加

npm install vue-router
// 執(zhí)行完后會(huì)自動(dòng)在package.json中添加
"vue-router": "^4.0.15"
// 如果區(qū)分dev或發(fā)布版本中使用,把上面添加的拷貝過去即可

2、在main.js中添加使用

(主要是下面第3/13行)

import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import router from '../router'
import 'element-plus/dist/index.css'
import './index.css'                    // 這個(gè)居中對(duì)齊了,不知道有哪些功能
import App from './App.vue'

const app = createApp(App)
// app.use(ElementPlus)
// app.mount('#app')
app
    .use(ElementPlus)
    .use(router)
    .mount('#app')

3、上面import的router需要在根目錄下

創(chuàng)建router文件夾,里面添加index.js文件

import {createRouter, createWebHashHistory} from "vue-router";
// import Home from "../views/test.vue";

const routes = [
    {
        path: '*',          // 默認(rèn)在Home頁面,沒有匹配到路由時(shí)使用
        redirect: '/Home'
    }, {
        path: '/',
        redirect: '/test'
    }, {
        path: '/test',
        name: 'test',
        // 上面importvue文件名后在''中添加名字即可,或按需引入
        component: () => import('../views/test.vue')
    }
]

const router = createRouter({
    // createWebHashHistory路徑有#號(hào),createWebHistory路徑不包含#。使用web方式部署到服務(wù)器刷新會(huì)報(bào)404錯(cuò)誤
    history: createWebHashHistory(),
    routes
});

// router.beforeEach((to, from, next) => {
//     document.title = `${to.meta.title} | vue-manage-system`;
//     const role = localStorage.getItem('ms_username');
//     if (!role && to.path !== '/login') {
//         next('/login');
//     } else if (to.meta.permission) {
//         // 如果是管理員權(quán)限則可進(jìn)入,這里只是簡(jiǎn)單的模擬管理員權(quán)限而已
//         role === 'admin'
//             ? next()
//             : next('/403');
//     } else {
//         next();
//     }
// });
export default router

4、在App.vue中添加顯示

// router-view顯示內(nèi)容
<template>
  <div id="app" >
    <router-view/>
  </div>
</template>

5、router-link路由鏈接

跳轉(zhuǎn)到指定位置

<!-- 字符串 -->
<router-link to="/home">Home</router-link>
<!-- 渲染結(jié)果 -->
<a href="/home" rel="external nofollow" >Home</a>

<!-- 使用 v-bind 的 JS 表達(dá)式 -->
<router-link :to="'/home'">Home</router-link>

<!-- 同上 -->
<router-link :to="{ path: '/home' }">Home</router-link>

<!-- 命名的路由 -->
<router-link :to="{ name: 'user', params: { userId: '123' }}">User</router-link>

<!-- 帶查詢參數(shù),下面的結(jié)果為 `/register?plan=private` -->
<router-link :to="{ path: '/register', query: { plan: 'private' }}">
  Register
</router-link>

6、如何根據(jù)router切換子窗體

嵌套路由,示例代碼:

 路由下加變量訪問

const User = {
  template: '<div>User {{ $route.params.id }}</div>',
}

// 這些都會(huì)傳遞給 `createRouter`
const routes = [{ path: '/user/:id', component: User }]

子路由(router-view顯示的內(nèi)容中還有router-view),如下需要配置默認(rèn)打開的子路由及顯示對(duì)應(yīng)子路由

const routes = [
  {
    path: '/user/:id',
    component: User,
    children: [
      // 當(dāng) /user/:id 匹配成功
      // UserHome 將被渲染到 User 的 <router-view> 內(nèi)部
      { path: '', component: UserHome },
      // ...其他子路由
      {
        // 當(dāng) /user/:id/profile 匹配成功
        // UserProfile 將被渲染到 User 的 <router-view> 內(nèi)部
        path: 'profile',
        component: UserProfile,
      },
      {
        // 當(dāng) /user/:id/posts 匹配成功
        // UserPosts 將被渲染到 User 的 <router-view> 內(nèi)部
        path: 'posts',
        component: UserPosts,
      },
    ],
  },
]

7、同級(jí)目錄下有多個(gè)顯示

  <ul>
    <li>
      <router-link to="/">First page</router-link>
    </li>
    <li>
      <router-link to="/other">Second page</router-link>
    </li>
  </ul>
  <router-view class="view one"></router-view>
  <router-view class="view two" name="a"></router-view>
  <router-view class="view three" name="b"></router-view>

路由配置如下

import { createRouter, createWebHistory } from 'vue-router'
import First from './views/First.vue'
import Second from './views/Second.vue'
import Third from './views/Third.vue'

export const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      // a single route can define multiple named components
      // which will be rendered into <router-view>s with corresponding names.
      components: {
        default: First,
        a: Second,
        b: Third,
      },
    },
    {
      path: '/other',
      components: {
        default: Third,
        a: Second,
        b: First,
      },
    },
  ],
})

不用路由,vue加載顯示

<template>
  <div>
    <Header/>
  </div>
</template>

<script>
import { useRouter } from "vue-router";
import Header from "../src/components/Header.vue";
import vTags from "../src/components/Tags.vue";
export default {
  components: {
    Header,
    vTags,
  },
}
</script>

嵌套路由時(shí)

<template>
  <div id="app">
    <router-view></router-view>
  </div>
</template>

<script>
import { useRouter } from "vue-router";
export default {
  methods:{
    clickMenu(item) {
      console.log(item);
      // console.log(item.name);
      this.$router.push({
        item
        // name: 'About'
      })
    }
  },
</script>

別人的教程代碼,主要是看注釋

import { createRouter } from'@naturefw/ui-elp'

import home from'../views/home.vue'

const router = {
  /**   * 基礎(chǔ)路徑   */
  baseUrl: baseUrl,

  /**   * 首頁   */
  home: home,

  menus: [
    {
      menuId: '1', // 相當(dāng)于路由的 name
      title: '全局狀態(tài)', // 瀏覽器的標(biāo)題
      naviId: '0', // 導(dǎo)航ID
      path: 'global', // 相當(dāng)于 路由 的path
      icon: FolderOpened, // 菜單里的圖標(biāo)
      childrens: [ // 子菜單,不是子路由。
        {
          menuId: '1010', // 相當(dāng)于路由的 name
          title: '純state',
          path: 'state',
          icon: Document,
          // 加載的組件
          component: () =>import('../views/state-global/10-state.vue')
          // 還可以有子菜單。
        },
        {
          menuId: '1020',
          title: '一般的狀態(tài)',
          path: 'standard',
          icon: Document,
          component: () =>import('../views/state-global/20-standard.vue')
        } 
      ]
    },
    {
      menuId: '2000',
      title: '局部狀態(tài)',
      naviId: '0',
      path: 'loacl',
      icon: FolderOpened,
      childrens: [
        {
          menuId: '2010',
          title: '父子組件',
          path: 'parent-son',
          icon: Document,
          component: () =>import('../views/state-loacl/10-parent.vue')
        }
      ]
    } 
  ]
}

exportdefault createRouter(router )

8、push、replace函數(shù)

router.push(location)

使用 router.push 方法。這個(gè)方法會(huì)向 history 棧添加一個(gè)新記錄,當(dāng)用戶點(diǎn)擊瀏覽器后退按鈕時(shí),可以返回到之前的URL,所以,等同于

router.replace()導(dǎo)航后不會(huì)留下 history 記錄。點(diǎn)擊返回按鈕時(shí),不會(huì)返回到這個(gè)頁面。

9、動(dòng)態(tài)路由

動(dòng)態(tài)路由主要通過兩個(gè)函數(shù)實(shí)現(xiàn)。router.addRoute() 和 router.removeRoute()。

它們只注冊(cè)一個(gè)新的路由,也就是說,如果新增加的路由與當(dāng)前位置相匹配,就需要你用 router.push() 或 router.replace() 來手動(dòng)導(dǎo)航,才能顯示該新路由。

之前在router文件夾下定義了router

const router = createRouter({
    // createWebHashHistory路徑有#號(hào),createWebHistory路徑不包含#并且無法刷新顯示(需要nginx適配)
    history: createWebHashHistory(),
    routes
});

添加路由,并手動(dòng)調(diào)用 router.replace() 來改變當(dāng)前的位置(覆蓋我們?cè)瓉淼奈恢茫?/p>

router.addRoute({ path: '/about', component: About })
// 我們也可以使用 this.$route 或 route = useRoute() (在 setup 中)
router.replace(router.currentRoute.value.fullPath)

如果你決定在導(dǎo)航守衛(wèi)內(nèi)部添加或刪除路由,你不應(yīng)該調(diào)用router.replace(),而是通過返回新的位置來觸發(fā)重定向:

router.beforeEach(to => {
  if (!hasNecessaryRoute(to)) {
    router.addRoute(generateRoute(to))
    // 觸發(fā)重定向
    return to.fullPath
  }
})

通過添加一個(gè)名稱沖突的路由。如果添加與現(xiàn)有途徑名稱相同的途徑,會(huì)先刪除路由,再添加路由(以下三種刪除方式):

// 這將會(huì)刪除之前已經(jīng)添加的路由,因?yàn)樗麄兙哂邢嗤拿智颐直仨毷俏ㄒ坏?
const removeRoute = router.addRoute(routeRecord)
// 刪除路由如果存在的話
removeRoute()
// 刪除路由
router.removeRoute('about')
// 添加路由
router.addRoute({ path: '/other', name: 'about', component: Other })

添加嵌套路由

router.addRoute({ name: 'admin', path: '/admin', component: Admin })
router.addRoute('admin', { path: 'settings', component: AdminSettings })

// 上面等效于如下實(shí)現(xiàn)方式
router.addRoute({
  name: 'admin',
  path: '/admin',
  component: Admin,
  children: [{ path: 'settings', component: AdminSettings }],
})

查看現(xiàn)有路由

Vue Router 提供了兩個(gè)功能來查看現(xiàn)有的路由:

  • router.hasRoute():檢查路由是否存在。
  • router.getRoutes():獲取一個(gè)包含所有路由記錄的數(shù)組。

10、動(dòng)態(tài)路由用于登錄

// 在login界面的事件中校驗(yàn)完成后,把用戶名和密碼存到本地,使用localStorage.getItem讀取
localStorage.setItem("ms_username", param.username);
// 登錄成功后觸發(fā)訪問其他頁面
router.push("/");

在router中添加如下處理。beforeEach:添加一個(gè)導(dǎo)航守衛(wèi),在任何導(dǎo)航前執(zhí)行。返回一個(gè)刪除已注冊(cè)守衛(wèi)的函數(shù)

router.beforeEach((to, from, next) => {
    document.title = `${to.meta.title} | vue-manage-system`;
    const role = localStorage.getItem('ms_username');
    if (!role && to.path !== '/login') {
        next('/login');
    } else if (to.meta.permission) {
        // 如果是管理員權(quán)限則可進(jìn)入,這里只是簡(jiǎn)單的模擬管理員權(quán)限而已
        role === 'admin'
            ? next()
            : next('/403');
    } else {
        next();
    }
});

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Vue中如何實(shí)現(xiàn)輪播圖的示例代碼

    Vue中如何實(shí)現(xiàn)輪播圖的示例代碼

    本篇文章主要介紹了Vue中如何實(shí)現(xiàn)輪播圖的示例代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-07-07
  • vue+spring boot實(shí)現(xiàn)校驗(yàn)碼功能

    vue+spring boot實(shí)現(xiàn)校驗(yàn)碼功能

    這篇文章主要為大家詳細(xì)介紹了vue+spring boot實(shí)現(xiàn)校驗(yàn)碼功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-05-05
  • vue隨機(jī)驗(yàn)證碼組件的封裝實(shí)現(xiàn)

    vue隨機(jī)驗(yàn)證碼組件的封裝實(shí)現(xiàn)

    這篇文章主要為大家詳細(xì)介紹了如何封裝一個(gè)隨機(jī)驗(yàn)證碼的VUE組件,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2020-02-02
  • Vue+Element實(shí)現(xiàn)頁面生成快照截圖

    Vue+Element實(shí)現(xiàn)頁面生成快照截圖

    這篇文章主要為大家詳細(xì)介紹了Vue如何結(jié)合Element實(shí)現(xiàn)頁面生成快照截圖功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2024-03-03
  • vue頁面設(shè)置滾動(dòng)失敗的完美解決方案(scrollTop一直為0)

    vue頁面設(shè)置滾動(dòng)失敗的完美解決方案(scrollTop一直為0)

    這篇文章主要介紹了vue頁面設(shè)置滾動(dòng)失敗的解決方案(scrollTop一直為0),本文通過場(chǎng)景分析實(shí)例代碼相結(jié)合給大家介紹的非常詳細(xì),需要的朋友可以參考下
    2023-05-05
  • el-date-picker 選擇日期范圍只保存左側(cè)日期面板的實(shí)現(xiàn)代碼

    el-date-picker 選擇日期范圍只保存左側(cè)日期面板的實(shí)現(xiàn)代碼

    接到這樣的需求,日期篩選,但限制只能選擇同一個(gè)月的數(shù)據(jù),故此應(yīng)該去掉右側(cè)月份面板,今天通過本文給大家分享el-date-picker 選擇日期范圍只保存左側(cè)日期面板的實(shí)現(xiàn)代碼,感興趣的朋友一起看看吧
    2024-06-06
  • Babel自動(dòng)生成Attribute文檔實(shí)現(xiàn)詳解

    Babel自動(dòng)生成Attribute文檔實(shí)現(xiàn)詳解

    這篇文章主要為大家介紹了Babel自動(dòng)生成Attribute文檔實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-11-11
  • vue 過濾器filter實(shí)例詳解

    vue 過濾器filter實(shí)例詳解

    VueJs 提供了強(qiáng)大的過濾器API,能夠?qū)?shù)據(jù)進(jìn)行各種過濾處理,返回需要的結(jié)果。這篇文章主要給大家介紹vue 過濾器filter實(shí)例,感興趣的朋友跟隨腳本之家小編一起學(xué)習(xí)吧
    2018-03-03
  • uni-app中App與webview雙向?qū)崟r(shí)通信詳細(xì)代碼示例

    uni-app中App與webview雙向?qū)崟r(shí)通信詳細(xì)代碼示例

    在移動(dòng)應(yīng)用開發(fā)中,uni-app是一個(gè)非常流行的框架,它允許開發(fā)者使用一套代碼庫構(gòu)建多端應(yīng)用,包括H5、小程序、App等,這篇文章主要給大家介紹了關(guān)于uni-app中App與webview雙向?qū)崟r(shí)通信的相關(guān)資料,需要的朋友可以參考下
    2024-07-07
  • Vue實(shí)現(xiàn)動(dòng)態(tài)樣式的多種方法匯總

    Vue實(shí)現(xiàn)動(dòng)態(tài)樣式的多種方法匯總

    本文要給大家介紹Vue實(shí)現(xiàn)動(dòng)態(tài)樣式的多種方法,下面給大家?guī)韼讉€(gè)案列,需要的朋友可以借鑒研究一下。
    2021-06-06

最新評(píng)論

鄂伦春自治旗| 新巴尔虎左旗| 渑池县| 灵台县| 上饶县| 乌鲁木齐市| 华宁县| 丰顺县| 蕉岭县| 和硕县| 共和县| 巨鹿县| 康保县| 林周县| 尼玛县| 张家界市| 长宁县| 南澳县| 全南县| 葫芦岛市| 丰台区| 乡城县| 和林格尔县| 辽源市| 贺州市| 三台县| 北票市| 江北区| 靖安县| 广南县| 乌拉特后旗| 武山县| 平武县| 贡山| 霍邱县| 福海县| 宁安市| 乐山市| 红桥区| 太仓市| 三台县|