mini vueRouter

1 篇文章 0 订阅

一个简单的 vue-router 的实现,不支持嵌套路由

export default class VueRouter {
    constructor ({ routres}) {
        this.routres = routres
        this.history = new History()
        this.path = window.location.hash // 初始化 path
        this.history.listen((path) => {
            this.path = path
            this.vm.$forceUpdata()
        })
    }

    init(vm) {
        this.vm = vm
    }
}

class History {
    listen (callback) {
        window.addEventListener('hashchange', function () {
            callback && callback(window.location.hash)
        })
    }
}

VueRouter.install = function (Vue) {
    Vue.mixin({
        beforeCreate () {
            this.$options.router && this.$options.router.init(this)
        }
    })
    // router-view
    Vue.component('router-view', {
        functional: true,
        render (createElement, { props, children, parent, data}) {
            const router = parent.$options.router
            const path = router.path
            const matchRouter = router.routres.find(router => {
                return router.path.replace(/^\//, '') === path.replace(/^#\//, '')
            })
            const matchComponent = matchRouter.component
            return createElement(
                matchComponent
            )
        }
    })
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
VueRouter 路由懒加载可以通过动态导入的方式实现,即在路由定义时通过 import() 函数异步加载组件。这样当用户访问该路由时,组件才会被加载,从而减少了首次加载时的文件大小和加载时间,提高了页面加载速度。 具体实现步骤如下: 1. 在路由定义时,将组件定义为一个函数,该函数通过 import() 函数动态加载组件。 ```js const router = new VueRouter({ routes: [ { path: '/about', component: () => import('./views/About.vue') } ] }) ``` 2. 在 webpack 中配置 babel-plugin-syntax-dynamic-import 插件,以支持 import() 函数动态导入语法。 ```js // webpack.config.js module.exports = { // ... module: { rules: [ // ... { test: /\.js$/, loader: 'babel-loader', options: { plugins: ['syntax-dynamic-import'] } } ] } } ``` 3. 在生产环境中开启路由懒加载,可以通过 webpack 的 SplitChunksPlugin 插件将路由组件打包成单独的文件,从而实现按需加载。 ```js // webpack.config.js const path = require('path') const { CleanWebpackPlugin } = require('clean-webpack-plugin') const HtmlWebpackPlugin = require('html-webpack-plugin') const MiniCssExtractPlugin = require('mini-css-extract-plugin') module.exports = { mode: 'production', entry: './src/main.js', output: { path: path.resolve(__dirname, 'dist'), filename: '[name].[contenthash].js', chunkFilename: '[name].[contenthash].js' }, module: { rules: [ // ... ] }, plugins: [ new CleanWebpackPlugin(), new HtmlWebpackPlugin({ template: './public/index.html' }), new MiniCssExtractPlugin({ filename: '[name].[contenthash].css' }) ], optimization: { splitChunks: { chunks: 'all' } } } ``` 这样就可以实现 VueRouter 路由懒加载了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值