vue中的计算属性computed

模板不再是简单的声明式逻辑。你必须看一段时间才能意识到,这里是想要显示变量 message 的翻转字符串。当你想要在模板中的多处包含此翻转字符串时,就会更加难以处理。所以,对于任何复杂逻辑,你都应当使用计算属性。

官方是这么阐述的,其实对于我们使涌多了也就不难理解了,就是说你自己定义在vue实例里的属性可以被用来计算然后你再使用,使用的场景也非常多,大多用于你的属性在动态的变化当中会用的很多的,需要计算属性,

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script type="text/javascript" src="vue.js"></script>
</head>

<body>
    <div id="vuediv">
    <button @click="reverseMsg">点击查看反转后的msg2</button>
    <div>{{msg2}}</div>
    <hr>
    <div>computed计算后的值:{{reverseMsgComputed}}</div>
    <hr/>
			商品单价:{{goodsPrice}} 
			购买数量<input type="button" value="-" v-on:click="goodsCount-=1" /><input type="text"   v-model:value="goodsCount" size=3 /><input v-on:click="goodsCount+=1" type="button" value="+" />
			<br/>
            <div>总金额为(cpmputed):{{totalPriceComputed}}</div>
            <div>总金额为(method):{{totalPrice()}}</div>
    </div>
</body>
<script>
    var vm = new Vue({
        el: "#vuediv",
        data() {
            return {
                msg: "1234567890",
                goodsCount: 1,
                goodsPrice: 8888.33,
                msg2: ''
            }
        },
        methods: {
            reverseMsg:function(){
               return this.msg2=this.msg.split('').reverse().join('');
            },
            totalPrice:function(){
                return (this.goodsCount*this.goodsPrice).toFixed(2);
            }
        },
        computed: {
             reverseMsgComputed:function(){
                 return this.msg.split('').reverse().join('');
             },
             totalPriceComputed:function(){
                 return (this.goodsPrice*this.goodsCount).toFixed(2);
             },
             totalPriceByGetSet:{
                 get(){

                 },
                 set(){
                     
                 }
             }
        },
        created:function(){
            alert("create被调用")
        }
    })
</script>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值