<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 的变量来实现状态切换。当 TodoButton 组件中的按钮被点击时,通过 emit 事件将选中的按钮的索引传递给父组件,父组件再将 active 变量更新为选中的索引,从而实现状态切换。</p>
<p>父组件示例代码:</p>
<template>
  <div>
    <TodoButton :active='active' @update:active='onUpdateActive' />
    <TodoList :todos='filteredTodos' />
  </div>
</template>
<script>
import TodoButton from './TodoButton.vue'
import TodoList from './TodoList.vue'

export default {
  name: 'App',
  components: {
    TodoButton,
    TodoList,
  },
  data() {
    return {
      active: 0,
      todos: [
        { id: 1, text: '学习Vue', completed: false },
        { id: 2, text: '学习React', completed: true },
        { id: 3, text: '学习Angular', completed: false },
      ],
    }
  },
  computed: {
    filteredTodos() {
      if (this.active === 0) {
        return this.todos
      } else if (this.active === 1) {
        return this.todos.filter(todo => todo.completed)
      } else if (this.active === 2) {
        return this.todos.filter(todo => !todo.completed)
      }
    },
  },
  methods: {
    onUpdateActive(index) {
      this.active = index
    },
  },
}
</script>
Vue 组件交互:使用按钮切换 Todo 列表状态

原文地址: https://www.cveoy.top/t/topic/mAQr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录