Vue 3.x 配置Vuex及Vant TabBar使用並將Vue3.x專案打包部署至tomcat
概述:Vant有很多可以直接使用的元件,但真正要實際使用,應用起來還是比較費勁,尤其對於初學者而言。透過Vuex來記錄選項卡狀態的變化,在TabBar元件頁面監聽,判斷當前頁面是哪個選項卡頁面,解決重新整理時,選項卡預設為第一個選項卡頁面的問題,本文主要解決配置及使用Vuex、Vant元件TabBar使用,以及Vue3.x專案釋出至Tomcat頁面重新整理404錯誤的問題。
一、 安裝vuex
使用yarn:yarn add vuex@next –save使用npmnpm install vuex@next --save
1、安裝命令yarn add vuex@next –save
2、安裝成功
3、新建store資料夾,在store資料夾下新建index.js
import { createStore } from 'vuex'const store = createStore({ state () { return { active: 0 //預設選中的選項卡 } }, mutations: { setActiveTabBar (state,value) { //console.info("store****:"+value) state.active=value } } }) export default store
4、全域性配置Vuex
在main.js全域性配置Vuex (在vue3.0中引入了一個新的函式名createApp,會把容器掛載到上面,因此會新命名一個變數const app = createApp(App),方便後期掛載依賴)
//匯入storeimport store from './store'app.use(store)app.mount('#app')
main.js配置如圖:
二 、使用TabBar
1、在components目錄下,新建TabBar.vue,供需要引用公共選項卡的頁面使用
<template> <van-tabbar v-model="active" route fixed> <van-tabbar-item icon="home-o" replace to="/main">首頁</van-tabbar-item> <van-tabbar-item icon="apps-o" replace to="/sort">分類</van-tabbar-item> <van-tabbar-item icon="browsing-history-o" replace to="/discover">發現</van-tabbar-item> <van-tabbar-item icon="cart-o" badge='99+' replace to="/cart">購物車</van-tabbar-item> <van-tabbar-item icon="user-o" dot to="/me">我的</van-tabbar-item> </van-tabbar></template><script>import { useStore } from "vuex";export default { name: "TabBar", setup() { const store = useStore(); const active = store.state.active; //console.info("setup active 值:"+active) return { active, }; }, watch: { $route(to) { /* 直接在TabBar元件頁面監聽,判斷當前頁面是哪個選項卡頁面, 解決重新整理時,選項卡預設為第一個選項卡的問題*/ //console.info("watch to:" + to.path); const navBarActive = to.path; if (navBarActive.includes("main")) { this.active = 0; } else if (navBarActive.includes("sort")) { this.active = 1; } else if (navBarActive.includes("discover")) { this.active = 2; } else if (navBarActive.includes("cart")) { this.active = 3; } else if (navBarActive.includes("me")) { this.active = 4; } this.$store.commit('setActiveTabBar', this.active); //console.info("####watch:" + this.active); }, }, };</script><style>.van-tabbar-item--active { /**自定義選項卡選中的顏色 */ color: #e10f02;} </style>
2、在views資料夾下,新建選項卡各頁面Main.vue(首頁),Sort.vue(分類),Discover.vue(發現),Cart.vue(購物車),Me.vue(我的),示例各頁面一樣,只改div裡面文字為對應頁面的中文,各頁面使用元件TabBar
3、執行效果
附:Vue3.x專案打包部署至tomcat
1、 打包命令:yarn build
2、 執行完畢,在專案目錄下生成dist
3、 複製dist下所有檔案至tomcat的webapp目錄下的ROOT目錄下:
4、 在ROOT目錄下,新建目錄WEB-INF,新建web.xml,解決重新整理,頁面報404錯誤
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaeehttp://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"version="3.1" metadata-complete="true"><display-name>Router for Tomcat</display-name> <error-page> <error-code>404</error-code> <location>/index.html</location> </error-page></web-app>