開發背景
公司需要開發一款移動端的app,奈何團隊沒有ios技術,工期比較短,所以選擇使用vue開發HTML5經過打包處理形成移動端app。
項目構思
1 項目整體使用Vue+HbuilderX開發
2 Vue實現基本頁面跳轉,增刪改查等app基本功能,當需要使用到app原生功能則使用mui.js
3 最後通過HbuilderX將vue項目打包成app包
開發實踐
1 運行打包app
這一步的步驟比較簡單,首先通過npm run build 命令打包vue項目,下面是vue打包配置
config/index.js
build: {
// Template for index.html
index: path.resolve(__dirname, '../demo/index.html'),
// Paths
assetsRoot: path.resolve(__dirname, '../demo'),
assetsSubDirectory: 'static',
assetsPublicPath: './',
/**
* Source Maps
*/
productionSourceMap: false, // 置爲false 減少項目體積
// https://webpack.js.org/configuration/devtool/#production
devtool: '#source-map',
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
}
router/index.js
import Vue from 'vue'
import Router from 'vue-router'
import Login from '../page/Login'
import Scroller from '../page/Scroller'
Vue.use(Router)
export default new Router({
base: 'demo',
// mode: 'history', 不能爲history模式 否則白屏
routes: [
{
path: '/',
name: 'Login',
component: Login
},
{
path: '/Scroller',
name: 'Scroller',
component: Scroller
}
]
})
打包完成之後,打開HbuilderX新建項目 選5+App類型,新建完成之後,刪除項目中除mainfest.json以外的所有文件,將vue項目打包後的文件打包過來,如圖
就能成功運行在手機上
2 引用mui.js
將mui.js導入至vue項目中, 在index.html中引用該js ,並在vue文件裏測試plus對象的方法,成功調用。
3 vue+mui.js實現再按一次退出功能
這裏不多說,直接上乾貨,哪個頁面需要再按一次退出功能直接引用該方法在create方法中調用即可
function hiddenGoback() {
// html5禁止返回上一頁
history.pushState(null, null, document.URL);
window.addEventListener("popstate", function () {
history.pushState(null, null, document.URL);
});
// muijs設置再按一次退出
mui.init(
{
keyEventBind: {
backbutton: true
}
}
);
let first = null;
mui.back = function () {
//判斷需要退出的頁面
if (window.location.toString().endsWith('Home') || window.location.toString().endsWith('#/') || window.location.toString().endsWith('Login')) {
//首次按鍵,提示‘再按一次退出應用’
if (!first) {
first = new Date().getTime();
mui.toast('再按一次退出');
setTimeout(function () {
first = null;
}, 1000);
} else {
if (new Date().getTime() - first < 1000) {
plus.runtime.quit();
}
}
return false;
}
}
}