wxmp v0.4.0
wxmp
一个 简单,轻量,贴近原生 的微信小程序开发框架,让小程序的开发变得更加便捷。
兼容小程序基础库 v2.0.1+。
功能
- 单文件组件,告别烦人的
.wxml,.wxss,.js,.json - 计算属性
使用
推荐使用标准模板 standard-wxmp,其中 script 使用 ES6,style 使用 Stylus,config 使用 YAML,template 使用 Pug。
完整示例
wxmp-todo-mvc 使用 wxmp 开发的 TodoMVC 小程序。
为什么会有这个项目
在这个项目之前,我们使用 mpvue 作为开发框架。长期使用以后,发现 mpvue 存在一些问题,其中最严重的问题是不够贴近原生。
小程序有自己的运行模型,这套模型和 Vue 并不相同,使用 Vue 的观念来开发小程序长期来看只会带来困扰。
mpvue 将小程序的接口全部屏蔽,这使得出错以后问题的排查变得十分困难。
我们期望有一个框架,能够
- 拥有像 Vue 一样便捷的开发体验
- 尽可能贴近小程序原生,因为如果想开发某个平台上最好的程序,唯一的方法是使用这个平台的原生开发
wxmp 并不复杂,实现也非常简单,但是它可以大幅增加我们的开发效率。
单文件组件
每个页面文件或者组件文件由四部分组成: template, style, config, script, 分别编译到小程序对应的 wxml, wxss, json, js。
注意,在页面中,使用 usingComponents 引用组件时,组件路径需要携带 /,根目录是 Webpack 中配置的 context。
如下是一个页面的示例:
<template>
.home
.home__main
_loading
_reserve-area
</template>
<script>
definePage({
onLoad() {
_showToast("Hello, World")
},
})
</script>
<config>
usingComponents:
_loading: /components/_loading
_reserve-area: /components/_reserve-area
</config>
<style>
.home
height: 100vh
display: flex
flex-direction: column
.home__main
flex: 1
</style>definePage && defineComponent
wxmp 定义了两个全局方法 definePage 和 defineComponent 用于取代小程序标准的 Page 和 Component 构造器。
新的构造器在原生的基础上增加了对 computed 配置项的支持,同时,definePage 中使用 methods 属性组织用户自定义方法,Page 构造器原生是不支持的。
definePage({
onLoad() ...
...
data: {
name: "wxmp",
age: 1,
},
computed: {
info(data) {
return `${ data.name } ${ data.age }`
},
},
methods: {
...
},
})defineComponent({
attached() ...
...
properties: {
num1: {
type: Number,
value: 1,
},
num2: {
type: Number,
value: 1,
},
},
computed: {
total(data) {
return data.num1 + data.num2
},
},
// Component 构造器原生支持 methods 属性
methods: {
...
},
}) 计算属性 & this.$set
在 definePage 和 defineComponent 中可以使用 computed 属性指定计算属性,wxmp 内部会追踪计算属性与数据属性之间的关系。
同时,wxmp 提供 this.$set 函数用于更新数据,该函数会自动计算计算属性的新值然后调用 setData。
注意,定义计算属性时,对数据属性的访问通过参数 data 实现。
definePage({
data: {
a: 1,
b: 1,
},
computed: {
c(data) {
return data.a + data.b
},
},
methods: {
dataChange() {
this.$set({ a: 2 }) // a 和 c 都会更新
},
},
})使用自定义解析引擎
可以在 Webpack 中配置不同的部分由什么 Loader 进行处理。
{
loader: "wxmp",
options: {
script: [{ loader: "babel-loader" }],
template: [
{
loader: "pug-plain-loader",
options: {
doctype: null, // 解决小程序中闭合标签不兼容的问题
},
},
],
style: [{ loader: "stylus-loader" }],
config: [{ loader: "yaml-loader" }],
},
},注意:
script必须提供config必须使用yaml-loader- 由于
pug会将div(wx:if="{{ 2 > 1 }}")转成{{ 2 > 1 }}, 无法被小程序识别,因此 wxmp 内部使用正则/="{{/g将="{{替换成!=\"{{, 以关闭 pug 转义
语法高亮
Sublime
下载 wxmp.sublime-syntax 文件,放入 Sublime 的 Packages/User 目录中。
打开 Command Palette,输入 Set Syntax: wxmp 即可。
VS Code
首先安装 Vue 的插件 vetur。
编辑 setting.json
"vetur.grammar.customBlocks": {
"config": "yaml",
"template": "pug",
"style": "stylus"
},
"files.associations": {
"*.wxmp": "vue"
},
"vetur.validation.template": false,
"vetur.validation.style": false,
"vetur.validation.script": false运行 Vetur: Generate grammar from vetur.grammar.customBlocks,然后重启 VS Code。
Authors
License
Released under the MIT license