Javascript Vue.js CLI 中的多个页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51692018/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
multiple pages in Vue.js CLI
提问by Martin Zahariev
I'm having trouble figuring out how to have multiple pages in a Vue CLI project. Right now I have my home page with a few components and I want to create another page but I do not know how to do that. Am I supposed to create multiple html files where the index.html by default is? In a simple file structure with css js img folder and html files as pages I know that creating another html file means making another page. But I don't understand how this works with Vue CLI project.
我无法弄清楚如何在 Vue CLI 项目中拥有多个页面。现在我的主页有几个组件,我想创建另一个页面,但我不知道该怎么做。我是否应该在默认情况下创建 index.html 所在的多个 html 文件?在使用 css js img 文件夹和 html 文件作为页面的简单文件结构中,我知道创建另一个 html 文件意味着创建另一个页面。但我不明白这如何与 Vue CLI 项目配合使用。
I saw stuff like vue-router and "pages" in Vue documentation but I do not understand them very well. What are my alternatives? Is there a guide that explains that in detail, because I wasn't able to find any, let alone detailed. Would be very happy if you could help! Thank you!
我在 Vue 文档中看到了诸如 vue-router 和“页面”之类的东西,但我不太了解它们。我的选择是什么?有没有详细解释的指南,因为我找不到任何指南,更不用说详细了。如果能帮到你会很开心!谢谢!
采纳答案by Hippolyte Fayol
Note pointing users to what should be the accepted answer
At the moment of posting my initial answer I wasn't aware of the possibility of actually building MPAs in VueJS. My answer doesn't address the question asked therefore I will recommend to take a look at the answer provided by PJ.Wanderson bellow which should be the accepted answer
请注意将用户指出什么应该是可接受的答案
在发布我的初始答案时,我不知道在 VueJS 中实际构建 MPA 的可能性。我的回答没有解决所提出的问题,因此我建议看看 PJ.Wanderson 提供的答案,这应该是公认的答案
Inital Answer
Vue.js projects are SPAs(single page applications). You only have one .htmlfile in the entire project which is the index.htmlfile you mentioned. The "pages" you want to create, in vue.js are referred to as components. They will be plugged into the index.htmlfile and rendered in the browser. A vue.js component comprises 3 parts:
初始答案
Vue.js 项目是 SPA(单页应用程序)。您.html在整个项目中只有一个文件,即index.html您提到的文件。您要创建的“页面”,在 vue.js 中被称为组件。它们将插入index.html文件并在浏览器中呈现。一个 vue.js 组件包括 3 部分:
<template>
</template>
<script>
export default {
}
</script>
<style>
</style>
- Template: it contains all the html your page should display (this is where you put the html of your pages)
- Script: it contains all JavaScript code that will be executed on the page/component
- Style: it contains the CSS that will style that specific component/page
- 模板:它包含您的页面应显示的所有 html(这是您放置页面 html 的位置)
- 脚本:它包含将在页面/组件上执行的所有 JavaScript 代码
- 样式:它包含将设置特定组件/页面样式的 CSS
You can check this tutorial out for a quick-start Vue.js 2 Quickstart Tutorial 2017
您可以查看本教程以获取Vue.js 2 快速入门教程 2017 的快速入门
It explains vue.js project structure and how the various files relate to each other
它解释了 vue.js 项目结构以及各种文件如何相互关联
回答by PJ.Wanderson
First: always read the official documentation. With Vue , you can build a SPA, as well: a MPA it no problem. Just follow the guide:
第一:始终阅读官方文档。使用 Vue,您还可以构建 SPA:MPA 没问题。只需按照指南:
- https://cli.vuejs.org/
- https://cli.vuejs.org/guide/html-and-static-assets.html#building-a-multi-page-app
- https://cli.vuejs.org/config/#pages
- https://cli.vuejs.org/
- https://cli.vuejs.org/guide/html-and-static-assets.html#building-a-multi-page-app
- https://cli.vuejs.org/config/#pages
Using Vue CLI 3, you can create a new project with vue create youProject, and set to manually configure it. Then, don't choose the SPA option. Vue will create a nice "start" project using a MPA approach. After that, just repeat the config on vue.config.js.
使用 Vue CLI 3,您可以使用 vue create youProject 创建一个新项目,并设置为手动配置它。然后,不要选择 SPA 选项。Vue 将使用 MPA 方法创建一个不错的“开始”项目。之后,只需在 vue.config.js 上重复配置即可。
Updated #1
更新 #1
It seems that some updates on Vue Cli, have changed the way to build a MPA app, so:
Vue Cli 的一些更新似乎改变了构建 MPA 应用程序的方式,因此:
- Create a new application
vue create test - Choose Manual configuration
- 创建一个新的应用程序
vue create test - 选择手动配置
The boilerplate created, will be a SPA one. But, make this changes:
创建的样板将是 SPA 样板。但是,进行以下更改:
Create a folder under
srcnamedpages(optional)Into this folder create your own pages: Home, About, etc.
- Copy and paste the App.vue and main.js from src, into your new folders - Home, etc.
- Format the
App.vueinto this folders, at your like - Create a vue.config.js and set like this: https://cli.vuejs.org/config/#pages
在
src命名下创建一个文件夹pages(可选)在此文件夹中创建您自己的页面:主页、关于等。
- 将 App.vue 和 main.js 从 src 复制并粘贴到您的新文件夹中 - Home 等。
- 根据
App.vue您的喜好将其格式化到此文件夹中 - 创建一个 vue.config.js 并像这样设置:https://cli.vuejs.org/config/#pages
Below, I have three image demonstrating this:
下面,我用三张图片来证明这一点:
- First: a fresh new app
- Second: this same app, with the changes I made above
- Third: the vue.config.js from this app
- 第一:一个全新的应用程序
- 第二:同一个应用程序,加上我在上面所做的更改
- 第三:来自这个应用程序的 vue.config.js
You don't need to create the pagesfolder, just get the idea.
您无需创建pages文件夹,只需了解一下即可。
Link to GitHub: Building a MPA App
GitHub 链接:构建 MPA 应用程序
回答by Andrew E
EDIT: Vue has this built-in. Skip to the bottom for more.
编辑:Vue 内置了这个。跳到底部了解更多。
Original answer:
原答案:
There are two ways to interpret your question, and therefore to answer it.
有两种方法可以解释您的问题,因此可以回答它。
The first interpretation is: "how can I support routing to different pages within the same single-page app, e.g. localhost:8080/about and localhost:8080/report etc?". The answer to this is to use the router. It's reasonably straightforward and works well.
第一种解释是:“我如何支持路由到同一个单页应用程序中的不同页面,例如 localhost:8080/about 和 localhost:8080/report 等?”。答案是使用路由器。它相当简单并且运行良好。
The second interpretation is: "my app is complex, and I have multiple single-page applications, e.g. one app for the 'website' part, one app for consumers to log in and do work, one app for admins, etc - how can vue do this, without making three entirely separate repositories?"
第二种解释是:“我的应用程序很复杂,我有多个单页应用程序,例如一个用于‘网站’部分的应用程序,一个用于消费者登录和工作的应用程序,一个用于管理员的应用程序,等等 - 怎么办? vue 在不制作三个完全独立的存储库的情况下做到这一点?”
The answer to the latter is a single repository with multiple single-page apps. This demo looks like exactly what you're after:
后者的答案是具有多个单页应用程序的单个存储库。这个演示看起来正是你所追求的:
https://github.com/Plortinus/vue-multiple-pages/
https://github.com/Plortinus/vue-multiple-pages/
Look in particular at: https://github.com/Plortinus/vue-multiple-pages/blob/master/vue.config.js
特别注意:https: //github.com/Plortinus/vue-multiple-pages/blob/master/vue.config.js
Updated answer:
更新的答案:
It turns out that vuejs has the idea of multiple top-level pages built-in. I mean, it makes sense - it's going to be really common, despite what many incorrect answers are saying about "no, it's for single page apps"!
原来vuejs有内置多个顶级页面的想法。我的意思是,这是有道理的 - 这将是非常普遍的,尽管许多不正确的答案都在说“不,它适用于单页应用程序”!
You want the pagesoption in the vue.config.jsfile:
您需要文件中的pages选项vue.config.js:
https://cli.vuejs.org/config/#pages
https://cli.vuejs.org/config/#pages
If your project doesn't have that file in the root directory, create it and vuejs will discover it.
如果您的项目在根目录中没有该文件,请创建它,vuejs 会发现它。
There is a long and a short way to define each page. I used the short form here:
定义每个页面的方法有长有短。我在这里使用了简短的形式:
module.exports = {
pages: {
index: 'src/pages/index/main.ts',
experiment: 'src/pages/experiment/main.ts'
}
}
You don't have to put your work under "pages". It could be "/src/apps/index/index.ts" or whatever.
你不必把你的工作放在“页面”下。它可以是“/src/apps/index/index.ts”或其他什么。
After moving code around and changing some imports from:
在移动代码并更改一些导入后:
import HelloWorld from './components/HelloWorld'
to
到
import HelloWorld from '@/components/HelloWorld'
The app works - but the "experiment" app in my repo had to be loaded like this:
该应用程序有效 - 但我的回购中的“实验”应用程序必须像这样加载:
http://localhost:8080/experiment.html
Pretty ugly, and even worse because it uses the router which resulted in URLs like:
非常丑陋,甚至更糟,因为它使用了导致 URL 如下的路由器:
http://localhost:8080/experiment.html/about
Ugh.
啊。
Fortunately, this stackoverflow answersolved it. Update the vue.config.jsfile to include devServeroptions (make sure this is at the top level of the exported object:
幸运的是,这个 stackoverflow 答案解决了它。更新vue.config.js文件以包含devServer选项(确保它位于导出对象的顶层:
devServer: {
historyApiFallback: {
rewrites: [
{ from: /\/index/, to: '/index.html' },
{ from: /\/experiment/, to: '/experiment.html' }
]
}
}
Then also modify the router.tsfile to append the extra path (in my case "experiment/":
然后还要修改router.ts文件以附加额外的路径(在我的情况下为“experiment/”:
export default new Router({
mode: 'history',
base: process.env.BASE_URL + 'experiment/',
...
Then URLs resolve nicely, e.g.: http://localhost:8080/experiment/about
然后 URL 解析得很好,例如:http://localhost:8080/experiment/about
回答by Ray's Life Thinking
This may not be relevant to the question, but bear with me, maybe my answer can help someone. I use webpack+vue, and I have figured out how to build multiple pages applications. Here my webpack.config.js:
这可能与问题无关,但请耐心等待,也许我的回答可以帮助某人。 我用的是webpack+vue,我已经弄清楚了如何构建多页面应用程序。这是我的 webpack.config.js:
const path = require('path');
const fs = require('fs')
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const TerserPlugin = require('terser-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
module.exports = {
entry: {
app: './src/app.js',
mgmt: ['./src/modules/mgmt/mgmt.js'],
login: './src/modules/login/login.js'
},
output: {
path: path.resolve(__dirname, 'dist'),
// publicPath: '/ahezime/',
filename: (chunkData) => {
console.log('chuckData.chunk.name => ', chunkData.chunk.name)
return chunkData.chunk.name === 'app' ? './[name].bundle.js' : './[name]/[name].bundle.js';
}
},
optimization: {
minimizer: [
new TerserPlugin(),
new OptimizeCSSAssetsPlugin({})
]
},
plugins: [
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
}),
new CleanWebpackPlugin(['dist']),
new VueLoaderPlugin(),
new HtmlWebpackPlugin({
title: 'app',
template: './src/app.html',
// inject: false,
chunks: ['app'],
filename: './index.html'
}),
new HtmlWebpackPlugin({
title: 'mgmt',
template: './src/modules/mgmt/mgmt.html',
// inject: false,
chunks: ['mgmt'],
filename: './mgmt/index.html'
}),
new HtmlWebpackPlugin({
title: 'login',
template: './src/modules/login/login.html',
// inject: false,
chunks: ['login'],
filename: './login/index.html'
})
],
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env'],
plugins: ['@babel/plugin-proposal-object-rest-spread']
}
}
}
],
rules: [
{
test: /\.vue$/,
exclude: /node_modules/,
loader: 'vue-loader'
},
{
test: /\.css$/,
use: [
'vue-style-loader',
'style-loader',
'css-loader',
'sass-loader'
]
},
{
test: /\.scss?$/,
use: ['style-loader', 'css-loader', 'sass-loader']
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: [
'file-loader'
]
}
]
}
};
And here's my directory structure:
这是我的目录结构:
https://i.stack.imgur.com/uFvKx.png
https://i.stack.imgur.com/uFvKx.png
And you can jump pages:
你可以跳转页面:
<template>
<div>
<h1>App</h1>
<div>
<a href="./login">Please click me, and let take you into the login page!!!</a>
</div>
<span>Before computed: {{ message }} </span>
<br>
<span>Afer computed: {{ computedMessage() }} </span>
</div>
</template>
<script>
export default {
data() {
return {
message: 'Hello World!'
}
},
computed: {
reversedMessage: function() {
return this.message.split('').reverse().join('')
}
},
methods: {
computedMessage: function() {
return this.message.split('').reverse().join('')
}
}
}
</script>
回答by user3873617
One easy solution
一个简单的解决方案
- Update your backend sever to either GET and/or POST
- axios.get/post(to_the_url)
- Serve back the html (like render_template in flask)
- You can extract the url from response.request.responseURL
- Now set window.location.href = response.request.responseURL
- 将您的后端服务器更新为 GET 和/或 POST
- axios.get/post(to_the_url)
- 返回 html(如 Flask 中的 render_template)
- 您可以从 response.request.responseURL 中提取 url
- 现在设置 window.location.href = response.request.responseURL


