mpvue创建包含fly, vuex, echarts,日历组件的初始化小程序工程

小程序mpvue初始化工程地址

在mpvue中使用flyio发起网络请求

  1. 安装

    npm install flyio -S

  2. 配置fly
    导入fly

let Fly = require('flyio/dist/npm/wx')
let fly = new Fly()

配置请求基地址以及拦截器

// 配置请求基地址
fly.config.baseURL = '/wechat'

// 添加请求拦截器
fly.interceptors.request.use((request) => {
  console.log(request)
  return request
})

// 添加响应拦截器
fly.interceptors.response.use(
  (response) => {
    console.log(response)
    return response
  },
  (err) => {
    return Promise.reject(err)
  }
)

挂载到Vue原型

Vue.prototype.$http = fly // 将fly实例挂在vue原型上,在每个vue文件中可以通过this.$http来进行访问

实例

export default {
  created () {
    // 调用API从本地缓存中获取数据
    const logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    console.log('app created and cache logs by setStorageSync')
  },
  mounted () {
    this.$http.get('/test').then((response) => {
      console.log(response)
    }).catch((error) => {
      console.log(error)
    })
  }
}

配置vuex

安装

npm install vuex -S

src目录下创建store目录
目录结构

store目录中index.js主要代码(与vue工程一致)

import Vue from 'vue'
import Vuex from 'vuex'

import mutations from './mutations'
import actions from './action'
import getters from './getters'

Vue.use(Vuex)

const state = {
  test: 0,
  userInfo: {}
}

export default new Vuex.Store({
  state,
  getters,
  actions,
  mutations
})

src目录main.js中导入并挂载到Vue原型

import store from './store'
Vue.prototype.$store = store // 将store挂载在Vue的原型上,这样可以在vue文件中访问this.$store

将vuex中的数据持久化到本地 (使用vuex-persistedstate)
- 安装vuex-persistedstate

npm install vuex-persistedstate -S

  • 在store目录下的index.js中配置插件
import Vue from 'vue'
import Vuex from 'vuex'

import createPersistedState from 'vuex-persistedstate'

import mutations from './mutations'
import actions from './action'
import getters from './getters'

Vue.use(Vuex)

const state = {
  test: 0,
  userInfo: {}
}

export default new Vuex.Store({
  state,
  getters,
  actions,
  mutations,
  plugins: [
    createPersistedState({
      storage: {
        getItem: key => wx.getStorageSync(key),
        setItem: (key, value) => wx.setStorageSync(key, value),
        removeItem: key => wx.clearStorage()
      }
    })
  ]
})

配置echarts

下载 echarts-for-weixin
把其 ec-canvas 目录移动到 mpvue 项目的 static 目录下。
ec-canvas/ec-canvas.js 进行小调整,考虑提 pr 到 ec-canvas。
修改 ready 为异步获取数据。

ready: function () {
  // 异步获取,将原有代码放入setTimeout中
    setTimeout(() => {
      if (!this.data.ec) {
        console.warn('组件需绑定 ec 变量,例:<ec-canvas id="mychart-dom-bar" '
          + 'canvas-id="mychart-bar" ec="{{ ec }}"></ec-canvas>');
        return;
      }

      if (!this.data.ec.lazyLoad) {
        this.init();
      }
    }, 10)
  }

为 init 添加接收 options 传参

var query = wx.createSelectorQuery().in(this);
      query.select('.ec-canvas').boundingClientRect(res => {
        if (typeof callback === 'function') {
          this.chart = callback(canvas, res.width, res.height);
        }
        else if (this.data.ec && this.data.ec.onInit) {
          this.chart = this.data.ec.onInit(canvas, res.width, res.height);
        }
        else if (this.data.ec && this.data.ec.options) {
        // 添加接收 options 传参,将最后这个else if添加到原有代码后面
          const ec = this.data.ec

          function initChart(canvas, width, height) {
            const chart = echarts.init(canvas, null, {
              width: width,
              height: height
            });
            canvas.setChart(chart);
            chart.setOption(ec.options);
            return chart;
          }
          this.chart = initChart(canvas, res.width, res.height);
        }
      }).exec();

创建 pages/bar 页面,目录如下:

.
└── pages
    └── bar
        ├── index.vue
        └── main.js

在 main.js 中引入微信小程序的自定义组件

import Vue from 'vue'
import App from './index'

const app = new Vue(App)
app.$mount()

// 添加 config json
export default {
  config: {
    // 这儿添加要用的小程序组件
    usingComponents: {
      'ec-canvas': '../../../static/ec-canvas/ec-canvas'
    }
  }
}

在 app.vue 中添加 options、template 等相关配置

<template>
  <div>
    <div class="container">
      <ec-canvas class="canvas" id="mychart-dom-bar" canvas-id="mychart-bar" :ec="ec"></ec-canvas>
    </div>
  </div>
</template>

<script>
const options = {
    // more code ... 
}

export default {
  data () {
    return {
      ec: {
        // 传 options
        options: options,
      }
    }
  }
}

</script>

<style>
ec-canvas {
  width: 400px;
  height: 400px;
}

</style>

适配mpvue平台的的微信小程序日历组件(mpvue-calendar)

安装

npm i mpvue-calendar -S

使用
- import Calendar from 'mpvue-calendar' 引入组件
- components中注册组件Calendar
- template中使用组件 <Calendar />

示例

<template>
  <div>
    <Calendar
      :months="months"
      :value="value"
      @next="next"
      @prev="prev"
      :events="events"
      lunar
      clean
      @select="select"
      ref="calendar"
      @selectMonth="selectMonth"
      @selectYear="selectYear"
      :arrowLeft="arrowLeft"
    />
    <button @click="setToday">返回今日</button>
  </div>
</template>

<script>
import Calendar from 'mpvue-calendar'
import arrowLeft from '../assets/arrowLeft.png'

export default {
  data () {
    return {
      months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
      disabledarr: ['2018-6-27','2018-6-25'],
      value: [2018,6,7],
      begin:[2016,1,1],
      end:[2020,1,1],
      events: {'2018-6-7':'今日备注', '2018-6-8':'一条很长的明日备注'},
      arrowLeft: arrowLeft
    }
  },
  components: {
    Calendar
  },
  methods: {
    selectMonth(month,year){
      console.log(year,month)
    },
    prev(month){
      console.log(month)
    },
    next(month){
      console.log(month)
    },
    selectYear(year){
      console.log(year)
    },
    setToday(val,val1,val2) {
      this.$refs.calendar.setToday();
    },
    select(val, val2) {
      console.log(val)
      console.log(val2)
    }
  }
}
</script>

图片
日历组件

猜你喜欢

转载自blog.csdn.net/roamingcode/article/details/81697500