vue中计算属性computed的使用


<template>
    <div>
        <h1>计算属性和监听属性</h1>
        <!--表达式太复杂会导致难以维护,而且如果多个地方使用该表达式会导致重复-->
        <div>
            {{type + "" +msg}}
        </div>

        <!--使用computed计算属性-->
        <div>{{type_msg}}</div>

        <hr>
        <div>{{firstName}}</div>
        <div>{{lastName}}</div>
        <div>{{fullName}}</div>
        <button @click="modifyFullName">修改fullName</button>
    </div>
</template>

<script>
    export default {
        name: "demo7",
        data(){
            return {
                type:"news",
                msg:"demo7",
                firstName:"zhang",
                lastName:'sanfeng'
            }
        },
        computed:{
            type_msg(){
                return this.type + ':' + this.msg
            },
            // fullName() {
            //     return this.firstName +":"+this.lastName
            // }
            fullName: {
                get(){
                    return this.firstName +":"+this.lastName
                },
                set(newVal){
                    console.log(newVal)
                    let arr= newVal.split(" ");
                    this.firstName = arr[0];
                    this.lastName = arr[1];

                }
                // return this.firstName +":"+this.lastName
            }
        },
        methods:{
            modifyFullName(){
                this.fullName ="xiao ming"
            }
        }
    }
</script>

<style scoped>

</style>

  

点击修改fullName按钮触发set方法,参数newVal接受的就修改后fullName值

效果图:


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM