How to change vue single page to multiple pages
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.
- 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.
- 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 } }
- 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.
- 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: '/' }, // ... }
- 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

React is the preferred tool for building interactive front-end experiences. 1) React simplifies UI development through componentization and virtual DOM. 2) Components are divided into function components and class components. Function components are simpler and class components provide more life cycle methods. 3) The working principle of React relies on virtual DOM and reconciliation algorithm to improve performance. 4) State management uses useState or this.state, and life cycle methods such as componentDidMount are used for specific logic. 5) Basic usage includes creating components and managing state, and advanced usage involves custom hooks and performance optimization. 6) Common errors include improper status updates and performance issues, debugging skills include using ReactDevTools and Excellent

React components can be defined by functions or classes, encapsulating UI logic and accepting input data through props. 1) Define components: Use functions or classes to return React elements. 2) Rendering component: React calls render method or executes function component. 3) Multiplexing components: pass data through props to build a complex UI. The lifecycle approach of components allows logic to be executed at different stages, improving development efficiency and code maintainability.

The React ecosystem includes state management libraries (such as Redux), routing libraries (such as ReactRouter), UI component libraries (such as Material-UI), testing tools (such as Jest), and building tools (such as Webpack). These tools work together to help developers develop and maintain applications efficiently, improve code quality and development efficiency.

The advantages of React are its flexibility and efficiency, which are reflected in: 1) Component-based design improves code reusability; 2) Virtual DOM technology optimizes performance, especially when handling large amounts of data updates; 3) The rich ecosystem provides a large number of third-party libraries and tools. By understanding how React works and uses examples, you can master its core concepts and best practices to build an efficient, maintainable user interface.

React is a front-end framework for building user interfaces; a back-end framework is used to build server-side applications. React provides componentized and efficient UI updates, and the backend framework provides a complete backend service solution. When choosing a technology stack, project requirements, team skills, and scalability should be considered.

React is a JavaScript library for building user interfaces, with its core components and state management. 1) Simplify UI development through componentization and state management. 2) The working principle includes reconciliation and rendering, and optimization can be implemented through React.memo and useMemo. 3) The basic usage is to create and render components, and the advanced usage includes using Hooks and ContextAPI. 4) Common errors such as improper status update, you can use ReactDevTools to debug. 5) Performance optimization includes using React.memo, virtualization lists and CodeSplitting, and keeping code readable and maintainable is best practice.

React's main functions include componentized thinking, state management and virtual DOM. 1) The idea of componentization allows splitting the UI into reusable parts to improve code readability and maintainability. 2) State management manages dynamic data through state and props, and changes trigger UI updates. 3) Virtual DOM optimization performance, update the UI through the calculation of the minimum operation of DOM replica in memory.
