vue实现收藏样式
vue实现收藏样式
使用图标库实现收藏样式
安装图标库如font-awesome或element-ui的图标组件,通过v-bind动态绑定类名或样式实现收藏与未收藏状态切换。
<template>
<i
class="icon"
:class="isCollected ? 'fas fa-star' : 'far fa-star'"
@click="toggleCollect"
></i>
</template>
<script>
export default {
data() {
return {
isCollected: false
}
},
methods: {
toggleCollect() {
this.isCollected = !this.isCollected
}
}
}
</script>
<style>
.icon {
color: gold;
cursor: pointer;
font-size: 24px;
}
</style>
使用CSS自定义样式
通过动态类名结合CSS实现自定义收藏样式,利用transform和transition添加动画效果。
<template>
<div
class="collect-btn"
:class="{ 'collected': isCollected }"
@click="toggleCollect"
></div>
</template>
<script>
export default {
data() {
return {
isCollected: false
}
},
methods: {
toggleCollect() {
this.isCollected = !this.isCollected
}
}
}
</script>
<style>
.collect-btn {
width: 30px;
height: 30px;
background: url('uncollected-icon.png');
cursor: pointer;
transition: transform 0.3s;
}
.collect-btn.collected {
background: url('collected-icon.png');
transform: scale(1.2);
}
</style>
使用SVG实现动态填充
通过SVG路径和动态绑定fill属性,实现更灵活的收藏样式控制。
<template>
<svg
width="24"
height="24"
viewBox="0 0 24 24"
@click="toggleCollect"
>
<path
:fill="isCollected ? 'gold' : 'none'"
stroke="gray"
stroke-width="1.5"
d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"
/>
</svg>
</template>
<script>
export default {
data() {
return {
isCollected: false
}
},
methods: {
toggleCollect() {
this.isCollected = !this.isCollected
}
}
}
</script>
结合Vuex管理收藏状态
在大型应用中,通过Vuex集中管理收藏状态,实现跨组件状态同步。
// store.js
export default new Vuex.Store({
state: {
collectedItems: []
},
mutations: {
toggleCollect(state, itemId) {
const index = state.collectedItems.indexOf(itemId)
if (index === -1) {
state.collectedItems.push(itemId)
} else {
state.collectedItems.splice(index, 1)
}
}
}
})
<template>
<button @click="toggleCollect(item.id)">
{{ isCollected ? '已收藏' : '收藏' }}
</button>
</template>
<script>
import { mapState, mapMutations } from 'vuex'
export default {
props: ['item'],
computed: {
...mapState(['collectedItems']),
isCollected() {
return this.collectedItems.includes(this.item.id)
}
},
methods: {
...mapMutations(['toggleCollect'])
}
}
</script>
添加收藏动画效果
通过Vue的transition组件或CSS动画库(如animate.css)增强交互体验。
<template>
<transition name="bounce">
<i
v-if="showIcon"
class="fas fa-heart"
:class="{ 'text-red-500': isCollected }"
@click="handleCollect"
></i>
</transition>
</template>
<style>
.bounce-enter-active {
animation: bounce-in 0.5s;
}
.bounce-leave-active {
animation: bounce-in 0.5s reverse;
}
@keyframes bounce-in {
0% { transform: scale(0); }
50% { transform: scale(1.5); }
100% { transform: scale(1); }
}
</style>





