Vue3.0 - computed函数

前言

computed计算属性,与普通JS函数相比computed性能更好,以为它存在计算缓存,js函数没有,其计算结果是只读的,可通过set方法修改。


computed的基本用法

<body>
    <div id="app">
        <input v-model="firstName" type="number"/>
        <input v-model="lastName" type="number"/>
        <div>{{fullName}}</div>
    </div>
</body>
<script>
    const {createApp, ref, computed} = Vue;
    const firstName = ref(1);
    const lastName = ref(2);

    const app = {
        // 入口函数
        setup() {
            // 基础用法
            let fullName = computed(() => firstName.value + lastName.value)
             // console.log(fullName ++) // error computed 是只读的
            return {
                firstName,
                lastName,
                fullName
            }
        }
    }

    // 挂载(建立vue与dom的联系)
    createApp(app).mount('#app')
</script>

computed的set和get方法

<body>
    <div id="app">
        <input v-model="firstName" type="number"/>
        <input v-model="lastName" type="number"/>
        <div>{{fullNames}}</div>
    </div>
</body>
<script>
    const {createApp, ref, computed} = Vue;
    const firstName = ref(1);
    const lastName = ref(2);

    const app = {
        // 入口函数
        setup() {
            // get set 方法
            const fullNames = computed({
                get: () => firstName.value + lastName.value,
                set: (val) => {
                    firstName.value = val
                }
            })
            fullNames.value = 7 // set
            return {
                firstName,
                lastName,
                fullNames
            }
        }
    }

    // 挂载(建立vue与dom的联系)
    createApp(app).mount('#app')

</script>

- End -
梦想是咸鱼
关注一下吧
posted @ 2021-09-10 14:46  Maggieq8324  阅读(572)  评论(0编辑  收藏  举报