VUE3頁面div如何點擊改變樣式
vue3頁面div點擊改變樣式
如題目所示。
用上VUE之后,前后端分離,組件式開發(fā),代碼復用、獨立性和隔離性都挺好,可維護性得以提高。
相比之下,以前用jQuery,代碼實在太多了。
不過,vue有個地方不大好,就是控制頁面元素的樣式比較死板?,F(xiàn)在用vue和react的話,基本都會選用一種UI框架,比如element plus,或者ant design等。
UI框架通常比較強大,效果也很煊,比自己動手寫強多了。
但如果有些自己還想額外加一些效果的話,就會發(fā)現(xiàn)困難重重,不像以前用jquery那么好控制。
比如,我想羅列 4 個div,代表4種分類。
點擊其中一個,就加上置亮的邊框;再點擊,取消置亮。
在ant design vue里找來找去,沒有這種控件,只好自己寫。
代碼如下:

<template>
<div class="c-container">
<div
v-for="(item, index) in items"
:key="index"
:class="
isActive === index
? 'c-item c-item-selected'
: 'c-item c-item-noselected'
"
:style="`background:url(各種圖標) no-repeat center 15px;`"
@click="changeCategory(item, index)"
>
<div class="c-text">{{ item.text }}</div>
</div>
</div>
</template><script>
import { defineComponent, toRefs, reactive, onMounted, ref } from "vue";
import { getCategory } from "@/components/Category";
import * as tools from "@/utils";
export default defineComponent({
setup(props, context) {
let isActive = ref(-1);
const changeCategory = (item, index) => {
if (isActive.value !== index) {//如果點擊的div沒有處于置亮狀態(tài),則置亮
isActive.value = index;
} else {//否則取消置亮
isActive.value = -1;
}
};
const state = reactive({
items: [],
});
onMounted(async () => {
state.items = 。。。;//獲取分類數(shù)據(jù)
});
return {
...toRefs(state),
changeCategory,
isActive,
};
},
});
</script><style scoped>
.c-container {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-around;
min-width: 390px;
}
.c-item {
width: 90px;
height: 90px;
margin-bottom: 10px;
border-radius: 5px;
cursor: pointer;
}
.c-item-noselected {
border: solid 1px #eee;
}
.c-item-selected {
border: solid 1px #1270d6;
}
.c-text {
margin-top: 60px;
}
</style>
代碼中主要用了isActive這個響應(yīng)式變量。
重點代碼為
:class="
isActive === index
? 'c-item c-item-selected'
: 'c-item c-item-noselected'
"
let isActive = ref(-1);
const changeCategory = (item, index) => {
if (isActive.value !== index) {//如果點擊的div沒有處于置亮狀態(tài),則置亮
isActive.value = index;
} else {//否則取消置亮
isActive.value = -1;
}
};
注意這個isActive,忽而isActive.value,忽而 isActive === index,讓人摸不著頭腦。
這是VUE的語法,沒辦法。
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue 實現(xiàn)通過vuex 存儲值 在不同界面使用
今天小編就為大家分享一篇vue 實現(xiàn)通過vuex 存儲值 在不同界面使用,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11
vue3實現(xiàn)tabs導航欄點擊每個導航項有下劃線動畫效果
這篇文章主要介紹了vue3實現(xiàn)tabs導航欄點擊每個導航項有下劃線動畫效果,本文通過實例代碼給大家介紹的非常詳細,感興趣的朋友跟隨小編一起看看吧2024-07-07
圖文詳解vue中proto文件的函數(shù)調(diào)用
這篇文章主要給大家介紹了vue中proto文件函數(shù)調(diào)用的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家學習或者使用vue具有一定的參考學習價值,需要的朋友可以參考下2021-08-08
如何在Vue3和Vite項目中用SQLite數(shù)據(jù)庫進行數(shù)據(jù)存儲
SQLite是一種嵌入式關(guān)系型數(shù)據(jù)庫管理系統(tǒng),是一個零配置、無服務(wù)器的、自給自足的、事務(wù)性的SQL數(shù)據(jù)庫引擎,這篇文章主要給大家介紹了關(guān)于如何在Vue3和Vite項目中用SQLite數(shù)據(jù)庫進行數(shù)據(jù)存儲的相關(guān)資料,需要的朋友可以參考下2024-03-03
vue跳轉(zhuǎn)頁面打開新窗口,并攜帶與接收參數(shù)方式
這篇文章主要介紹了vue跳轉(zhuǎn)頁面打開新窗口,并攜帶與接收參數(shù)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04

