前端学习-vue学习007-计算属性+Class 与 Style 绑定

官方教程链接

Class 与 Style 绑定

Vue 专门为 class 和 style 的 v-bind 用法提供了特殊的功能增强

<span :class="{done:item.done}">{{ item.text }}</span>

如果item.done是true,以上代码实际为

<span :class="done">{{ item.text }}</span>

如果item.done是false,以上代码实际为

<span :class="">{{ item.text }}</span>

computed计算属性

计算属性会自动跟踪其计算中所使用的到的其他响应式状态,并将它们收集为自己的依赖。计算结果会被缓存,并只有在其依赖发生改变时才会被自动更新。

<template>
  <div class="todo">
    <input type="text" placeholder="new todo" v-model="newTodo">
    <button @click="addTodo">Add Todo</button>
    <ul>
      <li v-for="item in filteredTodos" :key="item.id">
        <input type="checkbox" v-model="item.done">
        <span :class="{done:item.done}">{{ item.text }}</span>
        <button @click="delTodo(item)">X</button>
      </li>
    </ul>
    <button @click="hideCompleted = !hideCompleted">{{ hideCompleted ? 'show all' : 'hide completed'}}</button>
  </div>
</template>

<script setup lang="ts">
  import { reactive,ref,computed } from "vue";
  let id = 0
  let newTodo = ref()
  let todoList = ref(
    [
      {id:id++,text:"Learn HTML",done:true},
      {id:id++,text:"Learn CSS",done:false},
      {id:id++,text:"Learn VUE",done:true},
    ]
  )
  let hideCompleted = ref(false)
  let isHide = ref(false)
  function addTodo() {
    todoList.value.push({id:id++,text:newTodo.value,done:false})
    newTodo.value = ''
  }
  function delTodo(todo) {
    todoList.value = todoList.value.filter((t) => t !== todo)
  }
  const filteredTodos = computed(() => {
    return hideCompleted.value ? todoList.value.filter((t) => !t.done) : todoList.value
  })
</script>

<style>
.done {
  text-decoration: line-through;
}
</style>
posted @   ayubene  阅读(31)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示