NO2 setup体验

239 阅读1分钟
<template>

    <h1 @click="changeNum"> 计数器: {{ num }}</h1>

    <h1>用户名: {{user.username}}</h1>

    <h1 @click="changeType">特征: {{type}}</h1>

    <h1>特征翻转: {{reverseType}}</h1>

</template>


<script>

import {ref, reactive, toRefs, computed, watchEffect, watch} from 'vue'

export default {

    name'HelloWorld',

    setup() {

        const num = ref(0);

        function changeNum() {

            num.value+=10

        }

        const user = reactive({

            username'lmz',

            type'美! ',

            reverseTypecomputed(() => {

                return user.type.split('').reverse().join('')

            })

        }) 

        function changeType() {

            user.type = '帅!'

        }


        // 自动判断

        watchEffect(() => {

            console.log(user.type)

            console.log('当userType改变时,会触发执行此函数')

        })

        // 单独监听

        watch(num,(newNum, oldNum) => {

            console.log(newNum)

            console.log(oldNum)

            console.log('当num改变时,会触发执行此函数')

        })

        // 多个监听

        watch([num,user],(newNum, oldNum) => {

            console.log(newNum)

            console.log(oldNum)

            console.log('任意改变时,会触发执行此函数')

        })


        return {num, changeNum, user, ...toRefs(user),changeType}

    }

}

</script>