# 四、 WePY
框架开发规范与使用
# 001 - 如何设置默认首页
- 打开
src
->app.wpy
入口文件,将新创建的页面路径,注册到config
->pages
数组中,并调整为数组的第一项即可
pages: [
'pages/home',
'pages/index'
],
1
2
3
4
2
3
4
# 002 - 创建页面的注意事项
- 每个页面的
script
标签中,必须导入wepy
模块,并创建继承自wepy.page
的页面类;否则会报错。 - 每个页面的路径,必须记录到
app.wpy
的config
->pages
数组中。 - 页面路径记录完毕之后,必须再回到页面文件中,摁下
Ctrl + S
快捷键重新编译生成页面,否则会报错。
# 003 - 页面绑定事件以及传参
在
wepy
框架中,优化了事件绑定机制,支持类似于Vue.js
的事件绑定语法
- 在
WePY
中,统一使用@
绑定事件,传递参数直接采用@tap='handle()'
传递 - 案例代码
<button type='warn' @tap='handle({{age}})'>WePY 绑定事件</button>
1
data = {
age: 18
}
methods = {
handle: function (params) {
console.log('触发函数')
console.log(params)
}
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 004 - 页面绑定事件的注意事项
通过
@
符号绑定的事件处理函数,必须定义到页面的methods
节点下。
WePY
中的methods
属性只能声明页面wxml
标签的事件处理函数,不能声明自定义方法,- 自定义方法需要声明到和
methods
平级的节点位置,这与Vue
中的用法是不一致的。
data = {
age: 18
}
methods = {
handle: function (params) {
console.log('触发函数')
console.log(params)
this.add()
}
}
add () {
console.log('自定义事件')
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 005 - 页面以及文本框数据绑定
.wpy
页面中的私有数据,需要定义到 data 节点中,页面上使用双大括号语法 渲染 data 中的数据- 文本框与 data 做双向数据绑定需要定义事件
实现步骤如下:
①.为input输入框绑定数据和事件处理函数, 代码为: <input type="text" @input='inputHandle' value="" />
②.在methods中定义事件处理函数, 函数名称为 inputHandler
③.在事件处理函数中, 通过事件参数e.detail.value获取到最新的文本框内容
④.通过this.val = e.detail.value为data中的 msg 重新赋值
- 案例代码
<view>{{ age }}</view>
<input type="text" @input='inputHandle' value="{{ val }}" />
1
2
2
data = {
age: 18,
val: ''
}
methods = {
inputHandle: function (e) {
console.log(e.detail.value)
this.val = e.detail.value
}
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# 006 - wxs
脚本的使用
- 将
wxs
脚本定义为外联文件,并且后缀名为.wxs
- 在
<script></script>
标签内,通过import
导入相对路径的wxs
模块 - 在当前页面的
class
类中,通过wxs = { }
注册刚才导入的wxs
模块 - 案例代码
<view>{{ homeData.a }}</view>
1
import homeWxs from '../wxs/home.wxs'
export default class Home extends wepy.page {
wxs = {
homeData: homeWxs
}
}
1
2
3
4
5
6
7
2
3
4
5
6
7
注意: 被注册的wxs模块, 只能在当前页面的template中使用, 不能在script中使用
# 007 - 配置 promisify
启用 async
和 await
- 默认使用
wepy-cli
创建的项目,不支持使用ES7
的async
和await
来简化Promise API
的调用。 - 需要手动开启此功能:打开
src
->app.wpy
,找到constructor()
构造函数,在构造函数中代码的最后一行,添加this.use(‘promisify’)
constructor () {
super()
this.use('requestfix')
this.use('promisify') // 添加此行代码, 即可启用 async 和 await
}
1
2
3
4
5
2
3
4
5
# 008 - WePY
发送 get
和 post
请求
WePY
框架对原生小程序做了封装,之前通过wx
调用的API
,都可以直接使用wepy
进行调用
// wepy 发送 Get 请求
async getInfo () {
const res = await wepy.request('接口地址')
console.log(res)
}
1
2
3
4
5
6
7
2
3
4
5
6
7
// wepy 发送 Post 请求
async getInfo () {
const res = await wepy.request({
url: '接口地址',
method: 'post',
data: {
name: 'loong'
}
})
console.log(res)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# 009 - 异步更新数据
在异步函数中更新数据的时候,页面检测不到数据的变化,必须手动调用 this.$apply 方法。
作用是强制页面重新渲染
// 被 async 修饰的函数叫做异步函数
async getInfo() {
const res = await wepy.request('接口地址’)
this.getMsg = res.data
this.$apply()
}
1
2
3
4
5
6
7
2
3
4
5
6
7