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 --save1. 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 fly3. 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> @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中文网其它相关文章!
推荐阅读:
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!

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1
Powerful PHP integrated development environment

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
