Vue多页面应用开发

框架

浏览数:3,682

2017-12-23

  • 平时Vue只用来做单页面应用开发,其实它是可以做多页面开发的
  • Vue在工程化时,依赖webpack,webpack从一个入口文件将依赖的所有模块都整合在了一个页面
  • 所以要实现多页面开发,必须修改webpack的配置

配置步骤
  1.首先创建新页面的html文件、入口js、主组件vue
例如:

src\pages\brand\brand.html
src\pages\brand\brand.js
src\pages\brand\brand.vue

  2.配置入口,webpack可以配置多个入口

打开“\build\webpack.base.conf.js”文件,找到entry配置入口

entry: {
    app: './src/main.js',
    brand: './src/pages/brand/brand.js'
}

  3.配置开发环境,也就是run dev

打开“\build\webpack.dev.conf.js”,找到plugins,添加如下配置:

new HtmlWebpackPlugin({
    filename: 'brand.html',
    template: 'src/pages/brand/brand.html',
    inject: true,
    chunks: ['brand']
})
属性 描述 属性值
filename 生成的html文件名 ex:brand.html
template 指定模板生成html文件 ex:src/pages/brand/brand.html
inject 注入选项 true:script标签位于body底部,head:script标签位于head,false:不插入生成的js
favicon 给生成的 html 文件生成一个 favicon path/to/yourfile.ico
minify 是否对html进行压缩 {removeAttributeQuotes: true // 移除属性的引号} or false,默认为false
hash 给生成的 js 文件一个独特的 hash 值 默认为false
chunks 选项的作用主要是针对多入口(entry)文件,默认生成的html会引用所有的js文件,这个属性用来指定html引用指定的js ex:[‘brand’]
chunksSortMode 决定了 script 标签的引用顺序 dependency:按照依赖关系排序,{function}:传一个排序函数

  1.配置编译环境,也就是run build

打开\config\index.js文件,找到build,添加如下配置

brand: path.resolve(__dirname, '../dist/brand.html')

  2.配置生产环境

打开/build/webpack.prod.conf.js文件,找到plugins,添加如下配置

new HtmlWebpackPlugin({
    filename: config.build.brand,   //引用\config\index.js里的build
    template: 'brand.html',
    inject: true,
    minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeAttributeQuotes: true
    },
    chunksSortMode: 'dependency',
    chunks: ['manifest', 'vendor', 'brand']
}),

  3.编写入口文件

import Vue from 'vue'
import Brand from './brand.vue'
import '../../assets/stylus/reset.css'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
el: '#brand',
template: '<Brand/>',
components: { Brand }
})

  4.编写主组件




  5.运行,打开http://localhost:8080/brand.html看到效果

如需转载,请注明出处:http://www.aaronxue.top/2017/10/Vue多页面开发.html