MST

星途 面试题库

面试题:Vue中计算属性在模板使用的常见场景及优势

请举例说明Vue计算属性在模板中的常见使用场景,并阐述计算属性相比直接在模板中写表达式有哪些优势。
24.8万 热度难度
前端开发Vue

知识考点

AI 面试

面试题答案

一键面试

Vue计算属性在模板中的常见使用场景

  1. 数据格式化:例如展示日期,假设数据是时间戳,可通过计算属性将其格式化为常见日期格式 YYYY-MM-DD
<template>
  <div>
    <p>{{ formattedDate }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      timestamp: 1692345678
    };
  },
  computed: {
    formattedDate() {
      const date = new Date(this.timestamp * 1000);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    }
  }
};
</script>
  1. 复杂逻辑运算:购物车中计算商品总价,涉及单价、数量等多个变量的计算。
<template>
  <div>
    <p>商品总价: {{ totalPrice }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      productPrice: 50,
      quantity: 3
    };
  },
  computed: {
    totalPrice() {
      return this.productPrice * this.quantity;
    }
  }
};
</script>
  1. 数据过滤:在列表数据中,根据特定条件过滤出符合要求的数据展示。比如从用户列表中过滤出年龄大于18岁的用户。
<template>
  <div>
    <ul>
      <li v-for="user in adultUsers" :key="user.id">{{ user.name }}</li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      users: [
        { id: 1, name: 'Alice', age: 20 },
        { id: 2, name: 'Bob', age: 15 }
      ]
    };
  },
  computed: {
    adultUsers() {
      return this.users.filter(user => user.age > 18);
    }
  }
};
</script>

计算属性相比直接在模板中写表达式的优势

  1. 提高代码可读性:将复杂逻辑封装在计算属性中,模板代码更简洁直观。例如计算商品总价,如果在模板中写表达式 {{ productPrice * quantity }},对于复杂业务逻辑会使模板变得冗长难以维护;而使用计算属性 totalPrice,模板只关心结果展示,逻辑在 computed 中,代码结构更清晰。
  2. 缓存机制:计算属性会基于其依赖进行缓存,只有依赖数据发生改变时才会重新计算。例如上述 formattedDate 计算属性,只要 timestamp 不变,多次访问 formattedDate 不会重新执行计算函数,提高性能。而模板表达式每次重新渲染都会执行,若计算逻辑复杂会消耗性能。
  3. 便于复用:计算属性可以在多个地方复用,而模板中的表达式复用性较差。如上述 adultUsers 计算属性,在不同组件或同一组件不同位置,只要需要过滤出成年用户数据,都可直接使用该计算属性。