vue3_toRaw markRaw

703 阅读1分钟

官方文档

<template>
    <h2>toRaw markRaw</h2>
    <h3>state:{{state}}</h3>
    <button @click="testToRaw">测试toRaw</button>
    <button @click="testToMarkRaw">测试markRaw</button>
</template>

<script lang="ts">
import { defineComponent, markRaw, reactive, toRaw } from 'vue'

interface UserInfo {
    name: string
    age: number
    likes?: string[]
}
export default defineComponent({
    setup() {
        const state = reactive<UserInfo>({
            name: '小明',
            age: 20,
        })

        const testToRaw = () => {
            // 把代理对象变成普通对象,数据变化,界面不变化
            const user = toRaw(state)
            user.name += '='
            console.log('测试')
        }
        const testToMarkRaw = () => {
            // 没有markRaw,是可以修改的
            // state.likes = ['chi', 'he']
            // state.likes[0] += '='
            // console.log(state)

            // 加了markRaw,数据不能再被修改
            // markRaw标记的对象,从此以后都不能再成为代理对象
            const likes = ['chi', 'he']
            state.likes = markRaw(likes)
            setInterval(() => {
                if (state.likes) {
                    state.likes[0] += '='
                    console.log('tick')
                }
            }, 1000)
        }
        return { state, testToRaw, testToMarkRaw }
    },
})
</script>