页面和组件的注册
注册一个页面
如果使用 vscode,建议下载插件wxapp-helper
插件,就可以直接一键创建页面了,因为一个页面有 4 个文件还是比较麻烦的。
- 右键文件夹
新建小程序页面
, 比如我随便建个about
- 在
app.json
里面注册新建的页面即可
json
{
"pages": [
"pages/about/about"
],
}
1
2
3
4
5
2
3
4
5
- 然后就可以调用微信的 api 前往我们新注册的页面了
js
wx.navigateTo({
url: '/pages/about/about',
})
1
2
3
2
3
注册一个自定义组件组件
- 在根目录创建文件夹
components
- 右键文件夹选择
新建小程序组件
- 在需要使用的页面中注册组件
about.json
json
{
"usingComponents": {
"base-button": "/components/base-button/base-button"
}
}
1
2
3
4
5
2
3
4
5
组件传参和参数修改
- 先在子组件中定义参数,比如我下面要定义的就是一个
count
js
Component({
data: {},
properties: {
count: {
type: Number, // 简单的约定类型
value: 1, // 默认值
},
},
methods: {},
})
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
- 在父组件中使用
html
<base-button count="66" />
1
- 子组件修改父组件中的属性
在小程序中,修改父组件的属性的方法类似于 vue,子组件调用this.triggerEvent('eventName',params)
,父组件监听事件后进行修改
子组件中
html
<view class="base-button" bind:tap="clickCount">
I'm base button {{count}}
</view>
1
2
3
2
3
js
Component({
data: {},
properties: {
count: {
type: Number,
value: 1,
},
},
methods: {
clickCount() {
const { count } = this.data
this.triggerEvent(`changeCount`, { count })
},
},
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
父组件中
html
<base-button count="{{count}}" bind:changeCount="handleChangeCount" />
1
js
Page({
data: {
count: 1,
},
handleChangeCount(e) {
const { count } = e.detail
this.setData({
count: count + 1,
})
},
})
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
组件生命周期
关于组件生命周期在微信官方文档中已经很清晰了,这里就不再搬运
父组件获得子组件的实例
在小程序中或取子组件的示例十分简单,就像在浏览器中获取一个dom节点一样,然后就能调用子组件的方法了
html
<base-button class="button" />
1
js
Page({
bindComponentInstance(){
const child = this.selectComponent('.button');
child.click1()
},
onReady(){
this.bindComponentInstance()
}
})
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
小程序中的 tabbar
在小程序中可以使用配置的方法开启小程序的原生 tabbar 功能,原生 tabbar 会相对来说性能和兼容性更好
app.json
json
{
"tabBar": {
"color": "#e6e6e6",
"selectedColor": "#1677ff",
"backgroundColor": "#ffffff",
"position": "bottom",
"borderStyle": "black",
"list": [
{
"pagePath": "pages/index/index",
"text": "首页",
"iconPath": "assets/icons/tab/home.png",
"selectedIconPath": "assets/icons/tab/active-home.png"
},
{
"pagePath": "pages/logs/logs",
"text": "分类",
"iconPath": "assets/icons/tab/cate.png",
"selectedIconPath": "assets/icons/tab/active-cate.png"
},
{
"pagePath": "pages/profile/profile",
"text": "我的",
"iconPath": "assets/icons/tab/profile.png",
"selectedIconPath": "assets/icons/tab/active-profile.png"
}
]
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
WARNING
需要注意的是pagePath
和iconPath
这些字段,都不要以/
开头
也可以调用微信提供的一些钩子,来给tabbar一些特质的需求
比如隐藏或者显示tabbar , 或者给某个item加上红点,或者显示一些badge