http://mpvue.com/mpvue/

美团开源了mpvue

由于mpvue框架是完全基于Vue框架的(重写了其runtime和compiler)

运行时框架 runtime 和代码编译器 compiler 实现

mp:mini program 的缩写

mpvue:Vue.js in mini program

npm set registry https://registry.npm.taobao.org/
npm install vue-cli -g

开始创建项目

vue init mpvue/mpvue-quickstart mpvueTest

引入一些项目需要的基本第三方库

package.json,加入一下内容

  "dependencies": {
"mpvue": "^2.0.0",
"vuex": "^3.0.1",
"weapp-qrcode": "^0.9.0",
"flyio": "^0.5.9",
"install": "^0.12.2",
"mp-weui": "^1.0.3",
"mpvue-zanui": "^1.0.2",
"common-mpvue": "^0.4.6",
"mpvue-config-loader": "^0.1.3"
},

第三方库

import Vue from 'vue'
import App from './App'
import store from '@/store';
import WeUI from 'mp-weui/packages'; Vue.use(WeUI);
Vue.config.productionTip = false
App.mpType = 'app' const app = new Vue({
store,
...App
});
app.$mount();

main.json

{
"navigationBarTitleText": "页面标题",
"enablePullDownRefresh": true
}

utils目录下index.js常用方法:

// /**
// * 获取storage
// */
export function getCache(key) {
var value = wx.getStorageSync(key)
if (value) {
return value
}
return ""
} // /**
// * 删除storage
// */
export function removeCache(key) {
wx.removeStorage(key);
} /**
* 存储storage
*/
export function setCache(key, value) {
try {
wx.setStorageSync(key, value)
} catch (e) { }
} /**
获取url参数
*/
export function getUrlParam(path) {
var result = {},
param = /([^?=&]+)=([^&]+)/gi,
match;
while ((match = param.exec(path)) != null) {
result[match[1]] = match[2];
}
return result;
} /**
数组是否包含某个字符串
*/
export const carrContainStr = (a, obj) => {
for (var i = 0; i < a.length; i++) {
if (a[i] == obj) {
return i;
}
}
return -1;
} /**
克隆
*/
export const clone = (obj) => {
// Handle the 3 simple types, and null or undefined
if (null == obj || "object" != typeof obj) return obj; // Handle Date
if (obj instanceof Date) {
var copy = new Date();
copy.setTime(obj.getTime());
return copy;
} // Handle Array
if (obj instanceof Array) {
var copy = [];
for (var i = 0, len = obj.length; i < len; ++i) {
copy[i] = clone(obj[i]);
}
return copy;
} // Handle Object
if (obj instanceof Object) {
var copy = {};
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
}
return copy;
} throw new Error("Unable to copy obj! Its type isn't supported.");
} /**
判断机型
*/
export const isiOS = () => {
var u = navigator.userAgent;
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
if (isiOS) {
return true
}
return false;
}

https://vuex.vuejs.org/zh/guide/

flyio封装网络请求



flyio请求,封装代码

var Fly=require("flyio/dist/npm/wx")
import { getCache } from '../utils' const request = new Fly() // 全局加载提示 - 设定时间
let ltime = 0; function closeLoading(param) {
ltime--
}
request.interceptors.request.use((request) => {
// 全局加载提示 - 展示提示
// wx.showNavigationBarLoading()
ltime++ let dataSource = getCache("dataSource")
request.headers = {
"Content-Type": "application/x-www-form-urlencoded",
"source": "miniApp",
"dataSource": dataSource ? dataSource : ''
}
// 没用到
if (request.url.indexOf('getReviewInfo') != -1) {
closeLoading()
return request
}
// 登录
console.log('这是token');
console.log();
let type = '';
if(request.url.indexOf("wxLogin") != -1) {
type = request.body.loginType;
}
console.log(getCache("token"));
console.log('这是token');
if (request.url.indexOf("wxLogin") == -1 || type == 'WORKBENCH') {
// let storeId = getCache("storeId");
let storeCode = getCache("storeCode");
let inviter = getCache("inviter");
let token = getCache("token");
request.headers = {
"Content-Type": "application/x-www-form-urlencoded",
"source": "miniApp",
"token": token,
"storeCode": storeCode,
"inviter": inviter
}
console.log('打印request');
console.log(request);
console.log('打印request');
let dataSource = getCache("dataSource")
if (dataSource) {
request.headers['dataSource'] = dataSource
}
}
return request
}) request.interceptors.response.use((response, promise) => {
closeLoading()
// wx.hideNavigationBarLoading()
// 微信运维统计
if (response.status) {
wx.reportMonitor('0', +(response.status))
}
if (response.headers.date) {
let time = new Date().getTime() - new Date(response.headers.date).getTime()
wx.reportMonitor('1', +(time))
}
// 错误提示
if (response.status != 200) {
wx.showToast({
title: '出错啦!请稍后再试试哦~',
icon: 'none',
duration: 2000
})
}
return promise.resolve(response.data)
},
(err, promise) => {
wx.hideNavigationBarLoading()
return promise.resolve()
}
)
export default request

新建utils/api.js文件

 export const baseUrlApi = 'http://:8080'//---开发调试环境
//export const baseUrlApi = 'https://test.mini.com'//---测试环境https
//export const baseUrlApi = 'https://product.mini.com'//---生产环境https

src下新建service文件夹

login-service.js,order-service.js

import { baseUrlApi } from '../utils/api'
import request from '../utils/request' export default {
// 登录
wxLogin: (data) =>
request.post(`/store-miniApp-web/external/interface/wechat/wxLogin`, data, { baseURL: baseUrlApi }), // 收藏
addCollect: (goodId, status) =>
request.get(`/store-miniApp-web/store/member/addCollect?goodId=${goodId}&status=${status}`,
null, {
baseURL: baseUrlApi
}), }

接口请求的使用

import loginApi from "@/service/login-service";

  methods: {
//-登录
clickLoginBtn() {
var data = {
phone: '',
password: "",
};
console.log("登录参数==", data);
loginApi.wxLogin(data).then(
data => {
if (!data) {
this.$toast(data.msg);
return;
}
if (data.code==0) {
console.log("登录成功", data);
}
},
err => { }
);
},
//-收藏
collect() {
let isCollect = "1"; //1收藏 0取消
let goodId = "";
loginApi.addCollect(goodsId, isCollect).then(data => {
if (data.code != 0) {
console.log("收藏失败", data);
return;
}
if (isCollect == 1) {
this.$toast("取消成功");
} else {
this.$toast("收藏成功");
}
});
}
}

mapGetters

mapMutations

const store new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state,n){
state.count += n
}
}
}) new Vue({
el:"#app",
store,
computed: {
count() {
return store.state.count
}
},
methods: {
add() {
//传参
store.commit('increment',10)
}
}
})

mapMutations辅助函数的传参

//store.js
import Vue from 'vue'
import Vuex from 'vuex' Vue.use(Vuex) //定义state,并将listName设置为一个空对象
const state = {
listName: {}
}
//定义mutations,可以传参,用于设置state里的listName
const mutations = {
set_listname: (state,value) => {
state.listName=value
}
}
//定义getters,用于获取出state里的对象
const getters = {
get_listname: state => {
return state.listName
}
} export default new Vuex.Store({
getters,
state,
mutations
})

在vue实例中注册store

//main.js
import Vue from 'vue'
import App from './App'
import store from './store' /* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
template: '<App/>',
components: { App }
})



Fly.js

一个支持所有JavaScript运行环境的基于Promise的、支持请求转发、强大的http请求库。可以让您在多个端上尽可能大限度的实现代码复用。

https://wendux.github.io/dist/#/doc/flyio/readme

vuex的定义

Vuex 是一个专门为 Vue.js 应用程序开发的状态管理模式

集中存储和管理应用的所有组件的状态

store(仓库),new Vue.store({…})


请点赞!因为你的鼓励是我写作的最大动力!

吹逼交流群:711613774

最新文章

  1. bootstrap 3 中表单元素的写法 ---- 重点是 input file 元素的
  2. 用SpringMvc实现Excel导出功能
  3. WP8.1&amp;Win10开发:TextBox获取和失去焦点小技巧
  4. 将dataset写入数据库
  5. Android LCD(三):Samsung LCD接口篇
  6. 关于WIFI DIRECT功能的
  7. OpenVPN部署,实现访问云服务器的内网
  8. 通过JS如何获取IP地址
  9. Java集合操作精华总结
  10. 题解-拉格朗日(bzoj3695变种)
  11. pymysql 模块 使用目录
  12. py-faster-rcnn代码阅读3-roidb.py
  13. selectAll, unSelectAll两个操作的实现
  14. ASP.NET下跨应用共享Session和使用Redis进行Session托管
  15. Windows下CURL扩展无效之终极解决办法。
  16. shader内置变量
  17. 避免全表扫描的sql优化
  18. DDR4中的so-dimm 和component
  19. 快速解决Kali 更新失败问题
  20. SQL行转列 (及EAV模型获取数据)

热门文章

  1. bean标签解析与注册
  2. Java8新特性——Lambda表达式-1
  3. java之struts2之ServletAPI
  4. “SQL Server does not exist or access denied.”
  5. 【转载】 C#中List集合使用First()方法获取第一个元素
  6. javascript, 元素 页面 简单碰撞
  7. js中for循环点击事件(闭包)
  8. React 核心思想之声明式渲染
  9. DCL 管理用户
  10. 如何在backoffice里创建Hybris image container以及分配给product