Home >Web Front-end >JS Tutorial >How to build mpvue applet project

How to build mpvue applet project

php中世界最好的语言
php中世界最好的语言Original
2018-05-28 11:15:043226browse

This time I will show you how to build the mpvue applet project, and what are the precautions for building the mpvue applet project. The following is a practical case, let's take a look.

Preface

mpvue is an open source front-end framework developed by Meituan that has the same syntax as vue.js and can quickly develop small programs. The official website says that a set of codes can be used to achieve mini programs and H5 interfaces. Using this framework, developers will get a complete Vue.js development experience, while providing code reuse capabilities for H5 and mini programs. If you want to transform an H5 project into a small program, or if you develop a small program and want to convert it to H5, mpvue will be a very suitable solution.

Mpvue official website: http://mpvue.com/

demo address: https://github.com/ccwyn/mpvuedemo/tree/master/my-project

Why use mpvue

First of all, WeChat applet recommends a concise development method to complete lightweight product functions through multi-page aggregation. The mini program is downloaded locally as an offline package, loaded and started through the WeChat client. The development specifications are simple, the technology is thoroughly encapsulated, and it has its own development system. It is positioned as a simple logical view layer framework and is not officially recommended for development. Complex applications, but business requirements are difficult to simplify. Complex applications have higher requirements for development methods, such as components and modularization, automatic construction and integration, code reuse and development efficiency, etc. However, small program development specifications greatly limit these capabilities. Therefore, in order to solve the above problems, improve development efficiency, and provide a better development experience, WeChat applet is developed by using the mpvue framework based on Vue.js.

Features of mpvue

  1. Thorough component development capabilities: improve code

  2. Complete Vue.js development experience

  3. Convenient Vuex data management solution: easy to build complex applications

  4. Fast webpack construction Mechanism: Custom build strategy, hotReload during development phase

  5. Support the use of npm external dependencies

  6. Use Vue.js command line tool vue-cli fast

    Initialization project

  7. The ability of H5 code conversion and compilation into small program target code

Project Build

Project composition

1. Use mpvue official scaffolding to build the underlying structure of the project

2. Use Fly.js as the http request library
3. Use stylus as the project css preprocessing tool.

Project framework structure and filesDirectory structure

Mainly focus on the src directory where the application code is located

├── src // 我们的项目的源码编写文件
│ ├── components // 组件目录
│ │ └── head //导航组件
│ ├── config //公共配置
│ │ └── tips // 提示与加载工具类
│ ├── http //http请求配置文件
│ │ └── api // 接口调用文件
│ │ └── config //fly 配置文件
│ ├── pages //项目页面目录
│ ├── store //状态管理 vuex配置目录
│ │ └── actions.js //actions异步修改状态
│ │ └── getters.js //getters计算过滤操作
│ │ └── mutation-types.js //mutations 类型
│ │ └── mutations.js //修改状态
│ │ └── 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 // 主配置文件

Building process

1. Quickly create a small program through official documentshttp://mpvue.com/mpvue/

# 全局安装 vue-cli
$ npm install --global vue-cli
# 创建一个基于 mpvue-quickstart 模板的新项目
$ vue init mpvue/mpvue-quickstart my-project
# 安装依赖
$ cd my-project
$ npm install
# 启动构建
$ npm run dev

2. Open the dist directory with WeChat developer tools and check whether the page is displayed.

3. Configure fly

# npm安装 flyio
$ npm install flyio --save
1. Create the http directory under src. The directory structure is:

 │ ├── 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))};

4. Configure stylus

# npm安装 flyio
$ npm install stylus --save-dev
$ npm install stylus-loader --save-dev

1. Create the stylus directory under src. The directory structure is as follows :

 │ ├── stylus //stylus css处理器目录
 │ │ └── common.styl // 全局css样式
 │ │ └── index.styl // stylus 出口
 │ │ └── mixin.styl //mixin 方法
 │ │ └── reset.styl //reset css

2, mixin.stylus

Considering that it may be reused in h5 projects in the future, here is a unit conversion method [px2rem ], and does not use rpx which has platform differences. Even if it is migrated to the web in the future, it only needs to deal with the unit conversion logic of [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. Introduce

Introduce

<style lang="stylus" type="text/stylus" rel="stylesheet/stylus">
 @import "stylus/index.styl"
</style>
# in app.vue. If you want to use the method in mixin.stylus, you need to add it to the page. The stylus file refers to mixin.stylus

Five configuration config directory

1. Create the config directory under src. The directory structure is:

│ ├── 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
 });
 };
}
/**
 * 静态变量,是否加载中
 */
Tips.isLoading = false;

六、配置vuex

1、在src下 创建 store目录 目录结构为:

│ ├── store      //状态管理 vuex配置目录
│ │  └── actions.js    //actions异步修改状态
│ │  └── getters.js    //getters计算过滤操作
│ │  └── mutation-types.js    //mutations 类型
│ │  └── mutations.js    //修改状态
│ │  └── 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:当前状态树
  * 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 => {}
  }
 })
 ]
})

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

Vue.js实现表格增删步奏详解

如何使用PHP实现微信小程序人脸识别刷脸登录

The above is the detailed content of How to build mpvue applet project. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn