zoukankan      html  css  js  c++  java
  • mpvue搭建小程序框架

    http://mpvue.com/mpvue/

    美团开源了mpvue

    由于mpvue框架是完全基于Vue框架的(重写了其runtime和compiler)
    运行时框架 runtime 和代码编译器 compiler 实现

    mp:mini program 的缩写
    mpvue:Vue.js in mini program

    image.png

    image.png

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

    image.png

    开始创建项目

    vue init mpvue/mpvue-quickstart mpvueTest
    

    image.png

    image.png

    image.png

    image.png

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

    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"
      },
    

    image.png

    第三方库

    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封装网络请求

    image.png
    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 }
    })
    

    image.png
    image.png

    Fly.js

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

    image.png

    image.png

    image.png

    image.png

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

    vuex的定义

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

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

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


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

    官方微信公众号

    吹逼交流群:711613774

    吹逼交流群

  • 相关阅读:
    题解 nflsoj204 排列
    题解 CF1328 D,E,F Carousel, Tree Queries, Make k Equal
    题解 LOJ3277 「JOISC 2020 Day3」星座 3
    题解 nflsoj464 CF1267K 正睿1225:一个简单的计数技巧
    题解 CF1326F2 Wise Men (Hard Version)
    题解 CF1326E Bombs
    题解 CF1316E and UOJ495:一类结合贪心的背包问题
    仓鼠的DP课 学习笔记
    题解 CF1314B Double Elimination
    固件
  • 原文地址:https://www.cnblogs.com/dashucoding/p/11932379.html
Copyright © 2011-2022 走看看