How to build mpvue applet project
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
- Thorough component development capabilities: improve code
- Complete Vue.js development experience
- Convenient Vuex data management solution: easy to build complex applications
- Fast webpack construction Mechanism: Custom build strategy, hotReload during development phase
- Support the use of npm external dependencies
- Use Vue.js command line tool vue-cli fast
- 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 project2. 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
│ ├── http //http请求配置文件 │ │ └── api.js // 接口调用文件 │ │ └── config.js //fly 配置文件
//引入 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
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>
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中文网其它相关文章!
推荐阅读:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Fermat's last theorem, about to be conquered by AI? And the most meaningful part of the whole thing is that Fermat’s Last Theorem, which AI is about to solve, is precisely to prove that AI is useless. Once upon a time, mathematics belonged to the realm of pure human intelligence; now, this territory is being deciphered and trampled by advanced algorithms. Image Fermat's Last Theorem is a "notorious" puzzle that has puzzled mathematicians for centuries. It was proven in 1993, and now mathematicians have a big plan: to recreate the proof using computers. They hope that any logical errors in this version of the proof can be checked by a computer. Project address: https://github.com/riccardobrasca/flt

Share the simple and easy-to-understand PyCharm project packaging method. With the popularity of Python, more and more developers use PyCharm as the main tool for Python development. PyCharm is a powerful integrated development environment that provides many convenient functions to help us improve development efficiency. One of the important functions is project packaging. This article will introduce how to package projects in PyCharm in a simple and easy-to-understand way, and provide specific code examples. Why package projects? Developed in Python

Title: Learn more about PyCharm: An efficient way to delete projects. In recent years, Python, as a powerful and flexible programming language, has been favored by more and more developers. In the development of Python projects, it is crucial to choose an efficient integrated development environment. As a powerful integrated development environment, PyCharm provides Python developers with many convenient functions and tools, including deleting project directories quickly and efficiently. The following will focus on how to use delete in PyCharm

PyCharm is a powerful Python integrated development environment that provides a wealth of development tools and environment configurations, allowing developers to write and debug code more efficiently. In the process of using PyCharm for Python project development, sometimes we need to package the project into an executable EXE file to run on a computer that does not have a Python environment installed. This article will introduce how to use PyCharm to convert a project into an executable EXE file, and give specific code examples. head

How to Make a GroceryList on iPhone in iOS17 Creating a GroceryList in the Reminders app is very simple. You just add a list and populate it with your items. The app automatically sorts your items into categories, and you can even work with your partner or flat partner to make a list of what you need to buy from the store. Here are the full steps to do this: Step 1: Turn on iCloud Reminders As strange as it sounds, Apple says you need to enable reminders from iCloud to create a GroceryList on iOS17. Here are the steps for it: Go to the Settings app on your iPhone and tap [your name]. Next, select i

Implementing card flipping effects in WeChat mini programs In WeChat mini programs, implementing card flipping effects is a common animation effect that can improve user experience and the attractiveness of interface interactions. The following will introduce in detail how to implement the special effect of card flipping in the WeChat applet and provide relevant code examples. First, you need to define two card elements in the page layout file of the mini program, one for displaying the front content and one for displaying the back content. The specific sample code is as follows: <!--index.wxml-->&l

According to news from this site on October 31, on May 27 this year, Ant Group announced the launch of the "Chinese Character Picking Project", and recently ushered in new progress: Alipay launched the "Chinese Character Picking-Uncommon Characters" mini program to collect collections from the society Rare characters supplement the rare character library and provide different input experiences for rare characters to help improve the rare character input method in Alipay. Currently, users can enter the "Uncommon Characters" applet by searching for keywords such as "Chinese character pick-up" and "rare characters". In the mini program, users can submit pictures of rare characters that have not been recognized and entered by the system. After confirmation, Alipay engineers will make additional entries into the font library. This website noticed that users can also experience the latest word-splitting input method in the mini program. This input method is designed for rare words with unclear pronunciation. User dismantling

How uniapp can achieve rapid conversion between mini programs and H5 requires specific code examples. In recent years, with the development of the mobile Internet and the popularity of smartphones, mini programs and H5 have become indispensable application forms. As a cross-platform development framework, uniapp can quickly realize the conversion between small programs and H5 based on a set of codes, greatly improving development efficiency. This article will introduce how uniapp can achieve rapid conversion between mini programs and H5, and give specific code examples. 1. Introduction to uniapp unia
