微信小程序项目搭建(Vant Weapp)
1.引入vant组件库
- npm init -y
- npm i
- 后续看vant官网流程即可
注意:如果步骤没错,且重复试了很多遍。引用vant组件却发现组件不带样式,这种情况看看开发者工具是否是最新的稳定版,不是,请更新。
2.自定义tabBar
- 把tabBar切换的页面创建好,然后在app.json
"tabBar": {
"custom": true,
"list": [
{
"text": "首页",
"pagePath": "pages/index/index"
},
{
"text": "分类",
"pagePath": "pages/classify/classify"
},
{
"text": "购物车",
"pagePath": "pages/car/car"
},
{
"text": "我的",
"pagePath": "pages/my/my"
}
]
},
- 根目录下新建custom-tab-bar文件夹,然后新建index组件。icon文件夹存放的是自定义切换标签。
- index.js文件
// custom-tab-bar/index.js
Component({
data: {
active: 0,
list: [
{
text:"首页",
normal:"./icon/home.png",
active:"./icon/home-active.png",
url:"/pages/index/index"
},
{
text:"分类",
normal:"./icon/classify.png",
active:"./icon/classify-active.png",
url:"/pages/classify/classify"
},
{
text:"购物车",
normal:"./icon/car.png",
active:"./icon/car-active.png",
url:"/pages/car/car"
},
{
text:"我的",
normal:"./icon/my.png",
active:"./icon/my-active.png",
url:"/pages/my/my"
},
]
},
methods: {
onChange(e) {
// e.detail 的值为当前选中项的索引
wx.switchTab({url: this.data.list[e.detail].url})
},
init() {
const page = getCurrentPages().pop();
// 如果数组中某个子项的 url 等于 当前页面的路径 就返回这个子项的索引值
this.setData({
active: this.data.list.findIndex(item => item.url === `/${page.route}`)
});
}
}
})
- index.wxml文件
<van-tabbar
active="{{ active }}"
inactive-color="#bfbfbf"
active-color="#8f1a22"
bind:change="onChange">
<van-tabbar-item wx:for="{{ list }}" wx:key="index">
<image
slot="icon"
src="{{ item.normal }}"
mode="aspectFit"
style="width: 30px; height: 18px;"
/>
<image
slot="icon-active"
src="{{ item.active }}"
mode="aspectFit"
style="width: 30px; height: 18px;"
/>
{{ item.text }}
</van-tabbar-item>
</van-tabbar>
- 最后在每个tab页面js中
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
this.getTabBar().init()
},
注意:如果步骤全部正确,tabBar不显示出来,看看app.json里,有一个属性,把它删除就好
"lazyCodeLoading": "requiredComponents"