微信小程序taro Tabbar状态管理

前面虽然自定义了tabbar,但是状态管理没有做,导致tabbar的状态不对,这里做个状态管理,tabbar的状态管理,可以用的时候直接复制过来用即可。
按照vuex

nmp install vuex

vuex 版本是4.1.0,编写store.ts代码,放在app.ts同级目录,代码如下

import { createStore } from 'vuex'

const state = {
  selected: 0
}

const mutations = {
  SET_SELECTED (state, payload) {
    state.selected = payload
  }
}

const actions = {
  setSelected (context, index) {
    context.commit('SET_SELECTED', index)
  }
}

const getters = {
  getSelected(state) {
    return state.selected
  }
}

const store = createStore({
  state,
  mutations,
  actions,
  getters
})

export default store

app.ts 引入store,代码如下

import { createApp } from 'vue'
import './app.scss'
import store from './store'
const App = createApp({
  onShow (options) {},
  // 入口组件不需要实现 render 方法,即使实现了也会被 taro 所覆盖
})
App.use(store)
export default App

编写custom-tab-bar,index.vue代码,代码如下

<template>
  <nut-tabbar v-model="selected" @tab-switch="tabSwitch" bottom safe-area-inset-bottom placeholder>
    <nut-tabbar-item v-for="(item, index) in tabBarList" 
      :key="index" 
      :tab-title="item.title"
      :icon="item.icon"
      :to="item.url"></nut-tabbar-item>
  </nut-tabbar>
</template>

<script lang="ts">
 export default {
    options: {
      addGlobalClass: true 
    }
  }
</script>

<script lang="ts" setup>
import Taro from '@tarojs/taro'
import { ref,h,computed } from 'vue'
import { useStore } from 'vuex'
import { Home, Category, Find, Cart, My } from '@nutui/icons-vue-taro'
const store = useStore()
const selected = computed(() => store.getters.getSelected)
const tabBarList = [
  {
    title: '首页',
    icon: h(Home),
    url: '/pages/index/index',
    name: 'home'
  },
  {
    title: '我的',
    icon: h(My),
    url: '/pages/my/index',
    name: 'my'
  }
]

const tabSwitch = (item: Record<string, unknown>, index: number) => {
  console.log(item, index)
  setSelected(index)
  const url = item.to+""
  Taro.switchTab({ url })
}


function setSelected (index) {
  store.dispatch('setSelected', index)
}
</script>