0
点赞
收藏
分享

微信扫一扫

华为云GaussDB部署指南:主备架构的常见问题与解决方案

惠特曼 2024-07-24 阅读 1

1. Vue3中的computed函数

1.1. 什么是computed?
computed属性是Vue3中的一个响应式计算属性,它可以根据其他响应式数据的变化而自动更新其自身的值。computed属性可以接收一个计算函数,并在计算函数中使用其他响应式数据的值进行计算。当任何一个参与计算的响应式数据发生变化时,computed属性会自动重新计算其值,并触发相应的依赖更新。
1.2. 如何定义computed?
在Vue3中,你可以通过computed函数来定义一个计算属性。computed函数接收一个计算函数作为参数,并返回一个响应式的ref对象。

下面是一个使用computed函数形式用法的例子:实现日历翻月份功能
 

<template>
  <div>
    <button @click="prevMonth">上一月</button>
    <span>{{ currentMonth }}</span>
    <button @click="nextMonth">下一月</button>
    <ul>
      <li v-for="day in days" :key="day">{{ day }}</li>
    </ul>
  </div>
</template>
 
<script>
import { ref, computed } from 'vue';
 
export default {
  setup() {
    const currentDate = ref(new Date());
    const daysInMonth = computed(() => {
      const date = new Date(currentDate.value.getFullYear(), currentDate.value.getMonth(), 1);
      const days = new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
      return Array.from({ length: days }, (_, i) => i + 1);
    });
 
    const currentMonth = computed(() => {
      const date = currentDate.value;
      return `${date.getFullYear()}年${date.getMonth() + 1}月`;
    });
 
    function prevMonth() {
      currentDate.value = new Date(
        currentDate.value.getFullYear(),
        currentDate.value.getMonth() - 1,
      );
    }
 
    function nextMonth() {
      currentDate.value = new Date(
        currentDate.value.getFullYear(),
        currentDate.value.getMonth() + 1,
      );
    }
 
    return {
      currentMonth,
      daysInMonth,
      prevMonth,
      nextMonth,
    };
  },
};
</script>

这个例子包含了基本的日历展示,以及上一月和下一月的按钮用于翻页。setup函数中定义了响应式数据currentDate和计算属性currentMonthdaysInMonth,分别表示当前月份和天数列表。prevMonthnextMonth函数用于更新currentDate实现翻页功能。

举报

相关推荐

0 条评论