计算属性缓存 vs 方法的区别

文章介绍了Vue中计算属性和方法的区别,计算属性基于响应式依赖被缓存,性能更优,适用于需要缓存结果的情况;方法则在每次更新时都会执行,适合于无需缓存的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

计算属性

计算属性用来替代模版表达式,避免在模版中写臃肿的代码

计算属性值会基于其响应式依赖缓存,性能开销方面有优势。方法总是会在重渲染发生时再次执行函数。

<!DOCTYPE html>
<html lang="zh">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<meta http-equiv="X-UA-Compatible" content="ie=edge">
		<title></title>
	</head>
	<body>
		<script type="importmap">
			{
	    "imports": {
	      "vue": "https://unpkg.com/vue@3/dist/vue.esm-browser.js"
	    }
	  }
	</script>

		<div id="app">
			<input v-model="message" />
			<p>计算属性: {{publishedBooksMessage}}</p>
			<p>方法调用: {{calculateBooksMessage()}}</p>
		</div>

		<script type="module">
			import {
				createApp,
				ref,
				reactive,
				computed
			} from 'vue'

			createApp({
				setup() {
					const message = ref('Hello vue!')

					const author = reactive({
						name: 'John Doe',
						books: [
							'Vue 2 - Advanced Guide',
							'Vue 3 - Basic Guide',
							'Vue 4 - The Mystery'
						]
					})

					const publishedBooksMessage = computed(() => {
						console.log("computed")
						return author.books.length > 0 ? 'Yes' : 'No'
					})

					const calculateBooksMessage = () => {
						console.log("method")
						return author.books.length > 0 ? 'Yes' : 'No'
					}


					return {
						message,
						publishedBooksMessage,
						calculateBooksMessage,
					}
				}
			}).mount('#app')
		</script>
	</body>
</html>

input文本框随便输入,触发视图更新,当响应式数据author.books没有变化时,控制台可见,publishedBooksMessage计算属性getter函数只在初始化执行一遍,而calculateBooksMessage方法总会执行。此时适合用computed属性

<!DOCTYPE html>
<html lang="zh">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<meta http-equiv="X-UA-Compatible" content="ie=edge">
		<title></title>
	</head>
	<body>
		<script type="importmap">
			{
	    "imports": {
	      "vue": "https://unpkg.com/vue@3/dist/vue.esm-browser.js"
	    }
	  }
	</script>

		<div id="app">
			<input v-model="message" />
			<p>计算属性: {{computedNow}}</p>
			<p>方法调用: {{calcNow()}}</p>

		</div>

		<script type="module">
			import {
				createApp,
				ref,
				computed
			} from 'vue'

			createApp({
				setup() {
					const message = ref('Hello vue!')
					const computedNow = computed(() => {
						console.log("computed")
						return Date.now()
					})

					const calcNow = function() {
						console.log("method")
						return Date.now()
					}



					return {
						message,
						computedNow,
						calcNow,

					}
				}
			}).mount('#app')
		</script>
	</body>
</html>

当不需要缓存的场景时,推荐用method的方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值