vue中實現多頁面應用方式
vue實現多頁面應用
眾所都知vue是一個單頁面應用,但是單頁面應用最大的問題,就是首次加載的時候過慢,因為他要把所有的css,js都要下載下來后,才可以加載頁面,尤其是移動端,在弱網的情況下,體驗感極差
嘗試過很多種優(yōu)化的方式,就算在優(yōu)化css,js的體積,但是還是在100-200K的這么個容量,所以我想起能否用多頁面應用去解決這個問題。
首先你的會一些webpack
第一步
進入\build\webpack.base.conf.js目錄下,在module.exports的域里,找到entry
在那里配置添加多個入口:
// 文件路徑更具自己的實際情況進行配置,我這僅是 demo entry: { app: './src/main.js', one: './src/js/one.js', two: './src/js/two.js' },
這里的 one two 一定時要先在這里定義好的,后面是要用到的,好比 里面的app 不是隨便瞎寫的
第二步
對開發(fā)環(huán)境run dev里進行修改,打開\build\webpack.dev.conf.js文件,在module.exports那里找到plugins
下面寫法如下:
new HtmlWebpackPlugin({ filename: 'index.html', template: 'index.html', inject: true, chunks: ['app'] }), new HtmlWebpackPlugin({ filename: 'one.html', template: 'one.html', inject: true, chunks: ['one'] }), new HtmlWebpackPlugin({ filename: 'two.html', template: 'two.html', inject: true, chunks: ['two'] }),
這里的配置比較重要 ,如果沒寫好的 在打包的時候就會報錯了, 在chunks那里的app指的是webpack.base.conf.js的 entry 那里與之對應的變量名。
chunks的作用是每次編譯、運行時每一個入口都會對應一個entry,如果沒寫則引入所有頁面的資源。也就是沒有改項目配置前形成的單頁應用
第三步
對run build也就是編譯環(huán)境進行配置。首先打開\config\index.js文件,在build里加入這個:
index: path.resolve(__dirname, '../dist/index.html'), one: path.resolve(__dirname, '../dist/one.html'), two: path.resolve(__dirname, '../dist/two.html'),
這里也就是打包之后dist文件夾中形成的 html
第四步
打開/build/webpack.prod.conf.js文件,在 plugins 那里找到 HTMLWebpackPlugin,然后添加如下代碼:
其實復制粘貼改吧改吧就能用
new HtmlWebpackPlugin({ filename: config.build.index, template: 'index.html', inject: true, minify: { removeComments: true, collapseWhitespace: true, removeAttributeQuotes: true }, chunksSortMode: 'dependency', //(在這里和你上面chunks里面的名稱對應) chunks: ['manifest', 'vendor', 'app'] }), new HtmlWebpackPlugin({ filename: config.build.one, template: 'one.html', inject: true, minify: { removeComments: true, collapseWhitespace: true, removeAttributeQuotes: true }, chunksSortMode: 'dependency', chunks: ['manifest', 'vendor', 'one'] }),
其中filename引用的是\config\index.js里的build,每個頁面都要配置一個chunks,不然會加載所有頁面的資源。
上面的操作完成之后進行下面的傻瓜式操作 對咱們創(chuàng)建的文件進行碼代碼
one.js文件可以這樣寫:
import Vue from 'vue' import one from './one.vue' Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#one', render: h => h(one) })
one.vue寫法如下:
<template> <div id="one"> {{msg}} </div> </template> <script> export default { name: 'one', data () { return { msg: 'I am one' } } } </script>
tow 文件中的代碼一樣 我就不寫了
主要步驟我寫完了,咱們試試打包文件 輸入 npm run build 打包文件
沒有問題, 跑一下項目看看 npm run dev
會報一個錯,就是找不到文件
少了一步
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。