国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

詳解vue-router 初始化時做了什么

2024-05-06 15:33:28
字體:
供稿:網(wǎng)友

最近因?yàn)闃I(yè)務(wù)需要,實(shí)現(xiàn)了一個簡單的前端 router,正好也來看一下 vue router 是怎么實(shí)現(xiàn)的。這次先來一起看看 vue-router 初始化時做了什么。

vue router 的初始化使用步驟

我們首先來看 vue-router 的使用步驟,然后再分別去看各個步驟都發(fā)生了什么。

使用 vue-router 需要經(jīng)過一下幾個步驟:

引入 vue-router:

import VueRouter from 'vue-router';

利用 vue 的插件機(jī)制,加載 vue-router:

Vue.use(VueRouter);

實(shí)例化 VueRouter:

const router = new VueRouter({routes})

實(shí)例化 Vue:

const app = new Vue({router}).$mount('#app');

Vue 的插件機(jī)制

vue 提供了一個 use 方法,來加載插件:

Vue.use = function (plugin: Function | Object) { const installedPlugins = (this._installedPlugins || (this._installedPlugins = [])); if (installedPlugins.indexOf(plugin) > -1) {  return this; } // additional parameters const args = toArray(arguments, 1); args.unshift(this); if (typeof plugin.install === 'function') {  plugin.install.apply(plugin, args); } else if (typeof plugin === 'function') {  plugin.apply(null, args); } installedPlugins.push(plugin); return this;}

該方法首先檢查插件是否已經(jīng)加載,如果已經(jīng)加載,直接返回 this。

如果沒有加載過,會取所有的參數(shù),并將 this 放在第一個。優(yōu)先執(zhí)行 plugin.install 方法,若不能執(zhí)行,則直接執(zhí)行 plugin 自身。

最后將 plugin push 到插件列表中。

那么我們就需要看 VueRouter 的 install 方法做了什么,VueRouter 類定義在 src/index.js 文件中。

利用 vue 的插件機(jī)制,加載 vue-router

入口文件 index.js 對外 export 了一個 VueRouter 類。VueRouter 類包含了 router 的各種方法,我們直接先來看一下 install 方法。

install 方法在 index.js 中綁定在 VueRouter 類上:

import { install } from './install'VueRouter.install = install

它的實(shí)際實(shí)現(xiàn)是在 ./install.js 中,install 方法主要做了以下幾個事情:

1、設(shè)置了兩個 mixin:beforeCreate 和 destroyed。

Vue.mixin({ beforeCreate () {  if (isDef(this.$options.router)) {   this._routerRoot = this   this._router = this.$options.router   this._router.init(this)   Vue.util.defineReactive(this, '_route', this._router.history.current)  } else {   this._routerRoot = (this.$parent && this.$parent._routerRoot) || this  }  registerInstance(this, this) }, destroyed () {  registerInstance(this) }})

2、在 Vue 上綁定 $route 和 $router。

Object.defineProperty(Vue.prototype, '$router', { get () { return this._routerRoot._router }})Object.defineProperty(Vue.prototype, '$route', { get () { return this._routerRoot._route }})            
發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 黑河市| 壤塘县| 馆陶县| 岫岩| 云龙县| 永康市| 百色市| 青川县| 海淀区| 奈曼旗| 鄂尔多斯市| 沧州市| 教育| 呼图壁县| 石渠县| 东阳市| 叶城县| 涪陵区| 马关县| 郓城县| 石河子市| 中卫市| 平阳县| 金寨县| 大余县| 渝北区| 耿马| 大名县| 延庆县| 香港 | 丹寨县| 静海县| 宁德市| 夏津县| 永福县| 武宁县| 通江县| 宁夏| 松江区| 凌云县| 贡觉县|