Home  >  Article  >  Web Front-end  >  How to change vue single page to multiple pages

How to change vue single page to multiple pages

WBOY
WBOYOriginal
2023-05-24 10:54:071264browse

When using Vue for development, a single page application (SPA) is often used. This method has only one HTML page, all important components are dynamically loaded in this page, and Vue's router is used to present different view. However, there are situations where it is necessary to convert a single-page application to a multi-page application (MPA), which means creating a different HTML file for each view. In this article, we will discuss how to convert a Vue single-page application into a multi-page application.

  1. Configuring webpack

First we need to configure our MPA in webpack to ensure that each component can generate its own HTML file.

Through the webpack plug-in, we can configure an entry point for each view, and use the HtmlWebpackPlugin plug-in to generate an entry file for each HTML file and add a Script tag to the generated JS file. In this way, we can create an HTML file for each view as needed.

The following is a simple webpack configuration example:

module.exports = {
  entry: {
    home: './src/pages/home/main.js',
    about: './src/pages/about/main.js',
    contact: './src/pages/contact/main.js'
  },
  output: {
    path: './dist',
    filename: '[name].[hash].js'
  },
  plugins: [
    new HtmlWebpackPlugin({
      filename: 'home.html',
      template: './src/pages/home/index.html',
      chunks: ['home']
    }),
    new HtmlWebpackPlugin({
      filename: 'about.html',
      template: './src/pages/about/index.html',
      chunks: ['about']
    }),
    new HtmlWebpackPlugin({
      filename: 'contact.html',
      template: './src/pages/contact/index.html',
      chunks: ['contact']
    })
  ]
}

In the above code, we define three entry points and provide a template for each HTML file. Here we Use the HtmlWebpackPlugin to add the generated JS files to each HTML file.

  1. Routing configuration

Next we need to make some modifications to the routing to ensure that it can adapt to multi-page applications. We need to switch the Vue router to "history" mode so that extra "#" characters are not added to the route, and we need to modify the routing configuration to match it with the new HTML file name. We can accomplish the required changes by:

// main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import createRouter from '@/router'
import { sync } from 'vuex-router-sync'
import store from '@/store'

Vue.config.productionTip = false

const { app, router: createdRouter } = createRouter()

// sync the router with the vuex store
// this registers `store.state.route`
sync(store, createdRouter)

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  created() {
    const linkTags = document.getElementsByTagName('link')
    const links = Array.prototype.slice.call(linkTags)
    links.forEach(link => {
      const href = link.getAttribute('href')
      if (href && href.indexOf('.') !== -1) {
        link.setAttribute('href', `/public/pages/${[this.$route.path.split('/')[1]]}/${href}`)
      }
    })
  },
  render: h => h(App)
})

In the above code, we first import the createRouter() function and use it to create the application and router instances. We then sync the Vuex router with the Vue application and call the create() function to modify the href attribute of the a tags used to reference the static resources to ensure that they reference the correct CSS and JS files.

We also need to modify the router configuration to ensure that it maps to the correct HTML file, as shown below:

// router/index.js
import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/pages/home/Home.vue'
import About from '@/pages/about/About.vue'
import Contact from '@/pages/contact/Contact.vue'

Vue.use(Router)

export default function createRouter() {
  const router = new Router({
    mode: 'history',
    base: '/',
    routes: [
      {
        path: '/',
        redirect: '/home'
      },
      {
        path: '/home',
        name: 'Home',
        component: Home,
        meta: {
          title: 'Home Page'
        }
      },
      {
        path: '/about',
        name: 'About',
        component: About,
        meta: {
          title: 'About Page'
        }
      },
      {
        path: '/contact',
        name: 'Contact',
        component: Contact,
        meta: {
          title: 'Contact Page'
        }
      }
    ]
  })
  return { router }
}
  1. Determine the static resource path

After we convert a single-page application to a multi-page application, we need to ensure that all static assets are loaded correctly. In a single-page application, we usually reference all static resources into an HTML file, so we can set the output target of webpack to /dist in the root directory to ensure that all files can be correctly located in Access from multiple HTML pages.

  1. Writing the front-end code

After we have completed the above steps, we can now write the front-end code and use Vue for development. We can write independent components for each page, or use Vue component templates to share certain components. No matter which method we use, we need to make sure that the file name of each component and the file name of the HTML file match.

// Home.vue
<template>
  <div>
    <h1>Home page</h1>
    <p>Welcome to my home page!</p>
  </div>
</template>
<!-- home.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Home Page</title>
  <link rel="stylesheet" href="/public/pages/home/app.12345.css">
</head>
<body>
  <div id="app"></div>
  <script src="/public/pages/home/app.12345.js"></script>
</body>
</html>

Finally, make sure that publicPath is configured in webpack to correctly handle static resource paths. publicPath should point to the base path of each HTML file to ensure that each file can correctly load all the resources they need.

// webpack.config.js
module.exports = {
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'js/[name].[hash:8].js',
    publicPath: '/'
  },
  // ...
}
  1. Packaging and Deployment

Now we can use webpack to build our MPA as a set of files and deploy them to the website server. We need to generate a separate directory for each HTML file and create a common component for each directory. If we use Vue-cli 3.0, we can set the build configuration for the multi-page application by modifying the vue.config.js file as follows:

// vue.config.js
module.exports = {
  pages: {
    home: {
      entry: 'src/pages/home/main.js',
      template: 'public/pages/home/app.html',
      filename: 'home.html',
      chunks: ['chunk-vendors', 'chunk-common', 'home']
    },
    about: {
      entry: 'src/pages/about/main.js',
      template: 'public/pages/about/app.html',
      filename: 'about.html',
      chunks: ['chunk-vendors', 'chunk-common', 'about']
    },
    contact: {
      entry: 'src/pages/contact/main.js',
      template: 'public/pages/contact/app.html',
      filename: 'contact.html',
      chunks: ['chunk-vendors', 'chunk-common', 'contact']
    }
  }
}

In the above code, we have used the Vue CLI The "pages" attribute is provided, which allows us to configure different pages for each component and automatically generate the corresponding files for each page.

Now we have completed the creation and deployment of the multi-page application. In this way, we can handle a variety of pages very flexibly when building applications with Vue. We can add or remove pages as needed and create independent components for each page. Overall, this allows us to build more modular and maintainable applications.

The above is the detailed content of How to change vue single page to multiple pages. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn