如何学习vue的计算属性computed

本文深入探讨Vue中的计算属性computed,通过实例演示其如何基于响应式依赖进行缓存和重新计算,对比方法使用,提高前端开发效率。

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

vue的计算属性computed
任何复杂逻辑,在vue里都应当使用计算属性computed,计算属性是方法而不是属性,我们可以将同一函数定义为一个方法而不是一个计算属性。两种方式的最终结果确实是完全相同的。然而,不同的是计算属性是基于它们的响应式依赖进行缓存的。只在相关响应式依赖发生改变时它们才会重新求值。下面是一个小demo,有助于大家理解和运用computed属性

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="../node_modules/vue/dist/vue.js"></script>
		<style>
			li{list-style: none;}
			.active{background:red;}
		</style>
	</head>
	<body>
		<div id="app">
			<audio :src="getCurrentsong" autoplay="autoplay" controls="controls"></audio>
			<ul>
				<li v-for="(song,index) in musicData" :class="{active:index==currentIndex}"  @click="clickHandler(index)">
					<h2>{{song.id}}--{{song.name}}</h2>
					<h3>{{song.songSrc}}</h3>
				</li>
			</ul>
		</div>
		<script type="text/javascript">
			var musicData = [
			    {
			        id: 1,
			        name: "I believe",
			        songSrc: "../music/I believe.mp3",
			        author: "杨培安"
			    },
			    {
			        id: 2,
			        name: "一百万个可能.mp3",
			        songSrc: "../music/一百万个可能.mp3",
			        author: "Skot Suyama"
			    },
			    {
			        id: 3,
			        name: "I believe",
			        songSrc: "../music/I believe.mp3",
			        author: "杨培安"
			    }
			];
			new Vue({
				el:"#app",
				data(){
					return{
						musicData,
						currentIndex:0
					}
				},
				methods:{
					clickHandler(index){
						this.currentIndex=index;
					}
				},
				computed:{
					getCurrentsong:function(){
						return this.musicData[this.currentIndex].songSrc
					}
				}
			})
		</script>
	</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值