Vue.js 实现点击按钮切换状态示例:TodoButton 组件
<template>
<div class='button-container mt-3'>
<div class='btn-group' role='group' aria-label='Basic example'>
<button type='button' class='btn' :class="active === 0 ? 'btn-primary' : 'btn-secondary'" @click="onBtnClick(0) ">全部</button>
<button type='button' class='btn' :class="active === 1 ? 'btn-primary' : 'btn-secondary'" @click="onBtnClick(1)">已完成</button>
<button type='button' class='btn' :class="active === 2 ? 'btn-primary' : 'btn-secondary'" @click="onBtnClick(2)">待完成</button>
</div>
</div>
</template>
<script>
export default {
name: 'TodoButton',
emits: ['update:active'],
props: {
active: {
type: Number,
required: true,
default: 0,
}
},
methods: {
onBtnClick(index) {
if (index === this.active) return
this.$emit('update:active', index)
}
}
}
</script>
<style scoped>
.button-container {
margin-top: 30px;
margin-left: 80px;
width: 400px;
text-align: center;
}
.btn {
font-size: 20px;
height: 60px;
width: 80px;
margin-left: 50px;
background-color: powderblue;
border: 1px solid white;
}
.btn-group {
}
</style>
<p>如何实现点击不同按钮将不同状态进行展示内容:可以在父组件中使用子组件,并且在父组件中维护一个状态 active,用来表示当前选中的按钮。当子组件中的按钮被点击时,通过 emit 事件将选中的按钮的索引传递给父组件,父组件根据传递的索引更新 active 的值,从而实现根据不同按钮展示不同状态的功能。</p>
<p>例如,在父组件中可以使用 v-if 指令根据 active 的值来渲染不同状态的列表:</p>
<template>
<div>
<TodoButton :active="active" @update:active="onBtnClick" />
<div class="todo-list">
<div v-if="active === 0">
<!-- 渲染全部列表 -->
</div>
<div v-if="active === 1">
<!-- 渲染已完成列表 -->
</div>
<div v-if="active === 2">
<!-- 渲染待完成列表 -->
</div>
</div>
</div>
</template>
<script>
import TodoButton from './TodoButton.vue'
export default {
name: 'TodoList',
components: {
TodoButton
},
data() {
return {
active: 0 // 默认选中全部按钮
}
},
methods: {
onBtnClick(index) {
this.active = index
}
}
}
</script>
原文地址: https://www.cveoy.top/t/topic/mAP3 著作权归作者所有。请勿转载和采集!