基于mpvue的小程序項目搭建的步驟
前言
mpvue 是美團開源的一套語法與vue.js一致的、快速開發(fā)小程序的前端框架,按官網說可以達到小程序與H5界面使用一套代碼。使用此框架,開發(fā)者將得到完整的 Vue.js 開發(fā)體驗,同時為 H5 和小程序提供了代碼復用的能力。如果想將 H5 項目改造為小程序,或開發(fā)小程序后希望將其轉換為 H5,mpvue 將是十分契合的一種解決方案。
Mpvue官網:http://mpvue.com/
demo地址 :https://github.com/ccwyn/mpvuedemo/tree/master/my-project
為什么要用mpvue
首先微信小程序推薦簡潔的開發(fā)方式,通過多頁面聚合完成輕量的產品功能。小程序以離線包方式下載到本地,通過微信客戶端載入和啟動,開發(fā)規(guī)范簡潔,技術封裝徹底,自成開發(fā)體系,本身定位為一個簡單的邏輯視圖層框架,官方并不推薦用來開發(fā)復雜應用,但業(yè)務需求卻難以做到精簡。復雜的應用對開發(fā)方式有較高的要求,如組件和模塊化、自動構建和集成、代碼復用和開發(fā)效率等,但小程序開發(fā)規(guī)范較大的限制了這部分能力。所以為了解決上述問題,提高開發(fā)效率,提供更好的開發(fā)體驗,通過使用基于 Vue.js 的mpvue框架來開發(fā)微信小程序。
mpvue的特點
- 徹底的組件化開發(fā)能力:提高代碼
- 完整的 Vue.js 開發(fā)體驗
- 方便的 Vuex 數據管理方案:方便構建復雜應用
- 快捷的 webpack 構建機制:自定義構建策略、開發(fā)階段 hotReload
- 支持使用 npm 外部依賴
- 使用 Vue.js 命令行工具 vue-cli 快速初始化項目
- H5 代碼轉換編譯成小程序目標代碼的能力
項目搭建
項目構成
1、采用mpvue 官方腳手架搭建項目底層結構
2、采用Fly.js 作為http 請求庫
3、采用stylus作為項目css預處理工具。
項目框架結構和文件目錄結構
主要關注應用程序代碼所在的src目錄
├── src // 我們的項目的源碼編寫文件 │ ├── components // 組件目錄 │ │ └── head //導航組件 │ ├── config //公共配置 │ │ └── tips // 提示與加載工具類 │ ├── http //http請求配置文件 │ │ └── api // 接口調用文件 │ │ └── config //fly 配置文件 │ ├── pages //項目頁面目錄 │ ├── store //狀態(tài)管理 vuex配置目錄 │ │ └── actions.js //actions異步修改狀態(tài) │ │ └── getters.js //getters計算過濾操作 │ │ └── mutation-types.js //mutations 類型 │ │ └── mutations.js //修改狀態(tài) │ │ └── index.js //我們組裝模塊并導出 store 的地方 │ │ └── state.js //數據源定義 │ ├── stylus //stylus css處理器目錄 │ │ └── common.styl // 全局css樣式 │ │ └── index.styl // stylus 出口 │ │ └── mixin.styl //mixin 方法 │ │ └── reset.styl //reset css │ ├── untils //工具函數目錄 │ │ └── index.js │ ├── App.vue // APP入口文件 │ ├── main.js // 主配置文件
搭建過程
一、通過官方文檔 快速創(chuàng)建一個小程序http://mpvue.com/mpvue/
# 全局安裝 vue-cli $ npm install --global vue-cli # 創(chuàng)建一個基于 mpvue-quickstart 模板的新項目 $ vue init mpvue/mpvue-quickstart my-project # 安裝依賴 $ cd my-project $ npm install # 啟動構建 $ npm run dev
二、微信開發(fā)者工具打開dist目錄,查看頁面是否顯示。
三、配置 fly
# npm安裝 flyio $ npm install flyio --save
1、在src下 創(chuàng)建 http目錄 目錄結構為:
│ ├── http //http請求配置文件 │ │ └── api.js // 接口調用文件 │ │ └── config.js //fly 配置文件
2、config.js
//引入 fly
var Fly=require("flyio/dist/npm/wx")
var fly=new Fly;
//配置請求基地址
// //定義公共headers
// fly.config.headers={xx:5,bb:6,dd:7}
// //設置超時
// fly.config.timeout=10000;
// //設置請求基地址
// fly.config.baseURL="https://wendux.github.io/"
//添加攔截器
fly.interceptors.request.use((config,promise)=>{
//給所有請求添加自定義header
config.headers["X-Tag"]="flyio";
return config;
})
// Vue.prototype.$http=fly //將fly實例掛在vue原型上
export default fly
3、api.js
import fly from './config'
import qs from 'qs'
// 配置API接口地址
let root ='接口域名';
/**
* 接口模版====post
*
* export const test = params => {return fly.post(`${root}/xx/xx`, qs.stringify(params))};
*
* 接口模版====get
*
* export const test1 = function(){return fly.get(`${root}/api/getNewsList`)}
*
*
* 用法:
* 在 頁面用引入 test
* import {test} from '../../http/api.js'
*
* test(params).then(res=>{ console.log(res) })
*/
export const test = params => {return fly.post(`${root}/xx/xx`, qs.stringify(params))};
四、配置 stylus
# npm安裝 flyio $ npm install stylus --save-dev $ npm install stylus-loader --save-dev
1、在src下 創(chuàng)建 stylus目錄 目錄結構為:
│ ├── stylus //stylus css處理器目錄 │ │ └── common.styl // 全局css樣式 │ │ └── index.styl // stylus 出口 │ │ └── mixin.styl //mixin 方法 │ │ └── reset.styl //reset css
2、mixin.stylus
考慮到將來可能要復用到h5項目中 所以這里寫了一個 單位轉換的方法【px2rem】,并沒有使用存在平臺差異的rpx,以后即便遷移到web 端, 只需要處理【px2rem】的單位轉換邏輯就好
// 單行顯示省略號 no-wrap() text-overflow: ellipsis overflow: hidden white-space: nowrap // 多行顯示省略號 no-wrap-more($col) display: -webkit-box -webkit-box-orient: vertical -webkit-line-clamp: $col overflow: hidden //rem轉換 $px / 75 *1rem px2rem($px) $px * 1rpx
3、index.stylus
@import "./mixin.styl" @import "./reset.styl" @import "./common.styl"
4、引入
在 app.vue 中引入
<style lang="stylus" type="text/stylus" rel="stylesheet/stylus"> @import "stylus/index.styl" </style>
**如果要用到mixin.stylus中的方法,需要在頁面的stylus文件中 單獨引用 mixin.stylus
五 配置 config目錄
1、在src下 創(chuàng)建 config目錄 目錄結構為:
│ ├── config //公共配置 │ │ └── tips.js // 提示與加載工具類
2、tips.js
考慮到將來可能要復用到h5項目中 所以這里將微信提供的提示與加載框封裝成工具類,以后即便遷移到web 端, 只需要刪除tips.js的wx api就可以了。
可以在 main.js中引入,綁定到原型上
import Tips from './config/tip' Vue.prototype.$tips=Tips
在頁面中 this.$tips.alert("請輸入手機號")調用
/**
* 提示與加載工具類
*/
export default class Tips {
constructor() {
this.isLoading = false;
}
/**
* 彈出提示框
*/
static success(title, duration = 500) {
setTimeout(() => {
wx.showToast({
title: title,
icon: "success",
mask: true,
duration: duration
});
}, 300);
if (duration > 0) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, duration);
});
}
}
/**
* 彈出確認窗口
*/
static confirm(text, payload = {}, title = "提示") {
return new Promise((resolve, reject) => {
wx.showModal({
title: title,
content: text,
showCancel: true,
success: res => {
if (res.confirm) {
resolve(payload);
} else if (res.cancel) {
reject(payload);
}
},
fail: res => {
reject(payload);
}
});
});
}
static toast(title, onHide, icon = "success") {
setTimeout(() => {
wx.showToast({
title: title,
icon: icon,
mask: true,
duration: 500
});
}, 300);
// 隱藏結束回調
if (onHide) {
setTimeout(() => {
onHide();
}, 500);
}
}
/**
* 彈出加載提示
*/
static loading(title = "加載中") {
if (Tips.isLoading) {
return;
}
Tips.isLoading = true;
wx.showLoading({
title: title,
mask: true
});
}
/**
* 加載完畢
*/
static loaded() {
if (Tips.isLoading) {
Tips.isLoading = false;
wx.hideLoading();
}
}
static share(title, url, desc) {
return {
title: title,
path: url,
desc: desc,
success: function(res) {
Tips.toast("分享成功");
}
};
}
static alert (text, ok) {
if (ok === void 0) { ok = function (res) { }; }
if (!text) {
return;
}
wx.showModal({
content: text,
showCancel: false,
confirmColor: '#000000',
cancelColor: '#000000',
success: ok
});
};
}
/**
* 靜態(tài)變量,是否加載中
*/
Tips.isLoading = false;
六、配置vuex
1、在src下 創(chuàng)建 store目錄 目錄結構為:
│ ├── store //狀態(tài)管理 vuex配置目錄 │ │ └── actions.js //actions異步修改狀態(tài) │ │ └── getters.js //getters計算過濾操作 │ │ └── mutation-types.js //mutations 類型 │ │ └── mutations.js //修改狀態(tài) │ │ └── index.js //我們組裝模塊并導出 store 的地方 │ │ └── state.js //數據源定義
2、main.js中引入store, 并綁定到Vue構造函數的原型上,這樣在每個vue的組件都可以通過this.$store訪問store對象。
import store from './store' Vue.prototype.$store=store;
3、state.js
在數據源文件中定義變量:
const state={
test: 0,
}
export default state
4、mutation-types.js
在mutation-types.js中定義你的Mutation的名字
export const TEST = 'TEST' // 這是測試的
5、mutations.js
在mutations.js中寫處理方法
import * as types from './mutation-types'
const matations={
/**
* state:當前狀態(tài)樹
* data: 提交matations時傳的參數
*/
//是否有渠道
[types.TEST] (state,data) {
state.TEST = data;
},
}
export default matations
6、使用方法
# 在 store index.js 中引入
import Vue from 'vue';
import Vuex from 'vuex';
import state from './state'
import mutations from './mutations'
Vue.use(Vuex);
export default new Vuex.Store({
state,
mutations,
})
在頁面中引用

7、將vuex中的數據持久化到本地 (使用vuex-persistedstate)
# 安裝vuex-persistedstate $ npm install vuex-persistedstate --save
在 store index.js 引入
import Vue from 'vue';
import Vuex from 'vuex';
import state from './state'
import mutations from './mutations'
import createPersistedState from 'vuex-persistedstate'
Vue.use(Vuex);
export default new Vuex.Store({
state,
mutations,
plugins: [
createPersistedState({
storage: {
getItem: key => wx.getStorageSync(key),
setItem: (key, value) => wx.setStorageSync(key, value),
removeItem: key => {}
}
})
]
})
demo地址 :https://github.com/ccwyn/mpvuedemo/tree/master/my-project
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Vue中scrollIntoView()方法詳解與實際運用舉例
這篇文章主要給大家介紹了關于Vue中scrollIntoView()方法詳解與實際運用舉例的相關資料,該scrollIntoView()方法將調用它的元素滾動到瀏覽器窗口的可見區(qū)域,需要的朋友可以參考下2023-12-12
前端Vue全屏screenfull通用解決方案及原理詳細分析
這篇文章主要給大家介紹了關于前端Vue全屏screenfull通用解決方案及原理的相關資料,使用screenfull這一第三方庫可以實現更穩(wěn)定的全屏功能,需要的朋友可以參考下2024-10-10
ant design vue datepicker日期選擇器中文化操作
這篇文章主要介紹了ant design vue datepicker日期選擇器中文化操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-10-10
vue3中el-table實現多表頭并表格合并行或列代碼示例
這篇文章主要給大家介紹了關于vue3中el-table實現多表頭并表格合并行或列的相關資料,文中通過代碼介紹的非常詳細,對大家學習或者使用vue具有一定的參考借鑒價值,需要的朋友可以參考下2024-02-02

