1. 在 Vue3 中,可以使用 Vue Router 来实现多个页面之间的跳转。首先需要安装 Vue Router:
npm install vue-router
  1. 在 main.js 中引入 Vue Router 并注册:
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

const app = createApp(App)
app.use(router)
app.mount('#app')
  1. 在 router.js 中定义路由:
import { createRouter, createWebHistory } from 'vue-router'
import Home from './views/Home.vue'
import About from './views/About.vue'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    component: About
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

export default router
  1. 在 views 文件夹中创建 Home.vue 和 About.vue 组件:
<!-- Home.vue -->
<template>
  <div>
    <h1>Home Page</h1>
    <router-link to='/about'>Go to About Page</router-link>
  </div>
</template>

<script>
export default {
  name: 'Home'
}
</script>
<!-- About.vue -->
<template>
  <div>
    <h1>About Page</h1>
    <router-link to='/'>Go to Home Page</router-link>
  </div>
</template>

<script>
export default {
  name: 'About'
}
</script>
  1. 多页页面的文件结构可以按照以下方式组织:
src/
  views/
    Home.vue
    About.vue
  router.js
  main.js
  index.html
  about.html

其中,index.html 和 about.html 是两个不同的 HTML 页面,分别引入不同的 JavaScript 文件:

<!-- index.html -->
<!DOCTYPE html>
<html>
  <head>
    <title>Home Page</title>
  </head>
  <body>
    <div id='app'></div>
    <script src='js/home.js'></script>
  </body>
</html>
<!-- about.html -->
<!DOCTYPE html>
<html>
  <head>
    <title>About Page</title>
  </head>
  <body>
    <div id='app'></div>
    <script src='js/about.js'></script>
  </body>
</html>

在 webpack 配置中,需要配置多个 entry 和 output,以便生成多个 JavaScript 文件:

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

这样就可以在不同的 HTML 页面中分别加载不同的 JavaScript 文件,从而实现多页应用。

Vue3 多页面应用开发:路由配置、文件结构及多页面加载

原文地址: https://www.cveoy.top/t/topic/jzSP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录