How to use history mode for routing in vue multi-page project

Posted by Qnuts on Tue, 08 Oct 2019 21:08:08 +0200

Preface

Before writing a Vue project, we need to add a printed page. We need to use multi-page mode to develop it. It is easy for vue-cli3 to configure multi-page for initialized project. But we found that print.html can not configure the history mode routing, once using history mode routing. Writing a simple demo for help online did not solve the problem, and later there was no way to use the hash mode for the complete project.

How to solve

One day when I was looking at the webpack document, I suddenly saw the history ApiFallback configuration item, and I felt like I had found a way. After work, I went home and downloaded the previous project.
The previous configuration in vue.config.js was this.

const path = require('path')
function resolve (dir) {
  return path.join(__dirname, dir)
}
module.exports = {
    pages: {
        index: {
            entry: 'src/main.js',
            template: 'public/index.html',
            filename: 'index.html',
            title: 'Index Page',
        },
        print: {
            entry: 'src/print/main.js',
            template: 'public/print.html',
            filename: 'print.html',
            title: 'print Page',
        }
    },
    chainWebpack: config => {
        config.resolve.alias
            .set('@', resolve('src'))
            .set('assets',resolve('src/assets'))
            .set('components',resolve('src/components'));
    }
}

Then according to webpack document Add the following code:

configureWebpack: {
        devServer: {
            historyApiFallback: {
                verbose: true,
                rewrites: [
                    { from: /^\/index\/.*$/, to: '/index.html'},
                    {from: /^\/print\/.*$/, to: '/print.html'}
                ]
            }
        }
    }

Next, start the project to verify in the browser, and find that accessing localhost:8080/print/hello and localhost:8080/index/hello-world can access print.html and index.html pages respectively. But they can't enter the corresponding routing, so they modify their routing files. After the modification, the routes are as follows:

// print
import HelloWold from '../components/HelloWorld'
import goBack from '../components/GoBack'
export default [
    
    {
        path: '/print/hello',
        name: 'print',
        component: HelloWold
    },
    {
        path: '/print/go-back',
        name: 'print',
        component: goBack
    }
]
// index
import HelloWold from '../components/HelloWorld.vue'
export default [
    {
        path: '/index/hello-world',
        name: 'hello-world',
        component: HelloWold
    }
]

In the browser access, you can ~~~
Project address github

Topics: Javascript Vue Webpack github