【重要】小程序vant weapp+mobx实现tabbar

npm install 安装 vant weapp, mobx 的包,安装好了进行构建Npm (工具--构建npm)

npm install vant-weapp

npm install --save mobx-miniprogram@4.13.2 mobx-miniprogram-bindings@1.2.1

解释一下:这里的mobx-miniprogram 是 实例化, mobx-miniprogram-bindings是具体操作

app.json: (目的是 pages 创建文件夹 和 tabBar低版本兼容,特别是定制化的 custom:true)

{
  "pages": [
    "pages/home/home",
    "pages/user/user",
    "pages/index/index",
    "pages/logs/logs"
  ],
  "window": {
    "navigationBarTextStyle": "black",
    "navigationBarTitleText": "Weixin",
    "navigationBarBackgroundColor": "#ffffff"
  },
  "tabBar": {
    "custom": true,
   
    "list": [{
      "pagePath": "pages/home/home",
      "text": "首页"
    }, {
      "pagePath": "pages/user/user",
      "text": "我的"
    }]
  },
  "usingComponents": {
    "van-button":"@vant/weapp/button/index"
  },
  "componentFramework": "glass-easel",
  "sitemapLocation": "sitemap.json",
  "lazyCodeLoading": "requiredComponents"
}

创建 mobx 的全局状态管理:

创建store文件夹下的store.js

以下的目的是实例化Mobx: 并且设置参数的值和方法改变的值

import { observable, action } from 'mobx-miniprogram';

export const store = observable({
  activeTabBarIndex: 0,
  updateActiveTabBarIndex: action(function(index) {
    this.activeTabBarIndex = index;
  })
});

创建自定义的tabbar组件:

wxml:

<van-tabbar active="{{active}}"  bind:change="onChange">
  <van-tabbar-item  wx:for="{{ list }}" wx:key="index" icon="{{item.icon}}" >{{item.text}}</van-tabbar-item>
</van-tabbar>

index.js (引入mobx,并且开始设置全局共享的数据)
 

import { storeBindingsBehavior } from 'mobx-miniprogram-bindings';
import { store } from '../store/store';

Component({
  options: {
    styleIsolation: 'shared'
  },
  behaviors: [storeBindingsBehavior],

  storeBindings: {
    store,
    fields: {
      active: 'activeTabBarIndex'
    },
    actions: {
      updateActive: 'updateActiveTabBarIndex'
    }
  },

  data: {
    icon: {
      normal: 'https://img.yzcdn.cn/vant/user-inactive.png',
      active: 'https://img.yzcdn.cn/vant/user-active.png',
    },
    list: [{
      pagePath: '/pages/home/home',
      text: '首页',
      icon: 'home-o'
    }, {
      pagePath: '/pages/user/user',
      text: '我的',
      icon: 'user-o'
    }]
  },

  methods: {
    onChange(event) {
      this.updateActive(event.detail); // mobx更改值!!!
      wx.switchTab({
        url: this.data.list[event.detail].pagePath,
      });
    },
  }
});

index.json:

{
  "component": true,
  "usingComponents": {
    "van-tabbar": "@vant/weapp/tabbar/index",
    "van-tabbar-item": "@vant/weapp/tabbar-item/index"
  }
}

最后展示:

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值