Vue中computed、method的区别

Computed 的核心是"计算缓存"

  • 用于基于响应式数据计算新值

  • 缓存机制,依赖不变就不重新计算

  • 计算结果是响应式的(依赖变化会自动更新)

  • 适合模板中频繁使用的计算结果

method 普通方法

  • 普通函数,没有响应式特性

  • 每次调用都会执行

  • 适合事件处理、需要参数的操作

案例

使用方法拼接姓名

javascript 复制代码
<script setup>

import {computed, ref, watch} from "vue";
const firstName = ref("liu");
const lastName = ref("kang");

const fullName = () => {
  console.log("执行方法")
  return firstName.value + " " + lastName.value;
};
</script>

<template>
  全名:{{fullName()}}<br>
  全名:{{fullName()}}<br>
</template>

<style scoped>

</style>

控制台:

可见方法被调用几次就执行几次

使用计算属性拼接姓名

javascript 复制代码
<script setup>

import {computed, ref, watch} from "vue";
const firstName = ref("liu");
const lastName = ref("kang");
const fullName = computed(() => {
  console.log("执行computed")
  return firstName.value + " " + lastName.value;
});

</script>

<template>
  全名:{{fullName}}<br>
  全名:{{fullName}}<br>
</template>

<style scoped>

</style>

控制台:

在依赖并未发生改变的情况下,只执行一次计算属性

如果依赖发生改变的情况:

javascript 复制代码
<script setup>

import {computed, ref, watch} from "vue";
const firstName = ref("liu");
const lastName = ref("kang");
const fullName = computed(() => {
  console.log("执行computed")
  return firstName.value + " " + lastName.value;
});

</script>

<template>
  全名:{{fullName}}<br>
  全名:{{fullName}}<br>
  姓:<input type="text" v-model="firstName"/><br>
  名:<input type="text" v-model="lastName"/>
</template>

<style scoped>

</style>

一开始进入页面,执行一次computed

当依赖发生改变时,立马再次执行computed计算最新的值,改变一次重新计算一次

计算属性是否可以传参?

计算属性不可以传参,以下代码时错误用法:

javascript 复制代码
computed: {
  // 这是错误的!计算属性不能定义参数
  getItemPrice(item) {  // ❌ 不能这样写
    return item.price * this.taxRate
  }
}

// 模板中也不能传参
{{ getItemPrice(item) }}  // ❌ 不工作

如果想要传入参数,可以"曲线救国":

javascript 复制代码
// Vue3 组合式API
import { computed } from 'vue'

// 返回一个函数,该函数可以接收参数
const getItemPrice = computed(() => {
  // 返回一个函数,这个函数可以接收参数
  return (item) => {
    return item.price * taxRate.value
  }
})

// 使用
<template>
  <div v-for="item in items" :key="item.id">
    价格: {{ getItemPrice(item) }}
  </div>
</template>
相关推荐
小杨同学呀呀呀呀10 分钟前
Ant Design Vue <a-timeline>时间轴组件失效解决方案
前端·javascript·vue.js·typescript·anti-design-vue
qq_5324535314 分钟前
使用 Three.js 构建沉浸式全景图AR
开发语言·javascript·ar
华玥作者8 小时前
[特殊字符] VitePress 对接 Algolia AI 问答(DocSearch + AI Search)完整实战(下)
前端·人工智能·ai
Mr Xu_9 小时前
告别冗长 switch-case:Vue 项目中基于映射表的优雅路由数据匹配方案
前端·javascript·vue.js
前端摸鱼匠9 小时前
Vue 3 的toRefs保持响应性:讲解toRefs在解构响应式对象时的作用
前端·javascript·vue.js·前端框架·ecmascript
sleeppingfrog9 小时前
zebra通过zpl语言实现中文打印(二)
javascript
lang201509289 小时前
JSR-340 :高性能Web开发新标准
java·前端·servlet
好家伙VCC10 小时前
### WebRTC技术:实时通信的革新与实现####webRTC(Web Real-TimeComm
java·前端·python·webrtc
未来之窗软件服务10 小时前
未来之窗昭和仙君(六十五)Vue与跨地区多部门开发—东方仙盟练气
前端·javascript·vue.js·仙盟创梦ide·东方仙盟·昭和仙君
baidu_2474386110 小时前
Android ViewModel定时任务
android·开发语言·javascript