vue3.0中的toRaw和markRaw
vue3.0中的toRaw和markRaw
·
toRaw将代理对象变成普通对象,数据发生变化,不会更新
markRaw标记的对象数据,从此以后再也不能成为代理对象了
两者区别:toRaw会将整个对象变成非响应式的,markRaw可以指定哪些属性值可以变化,
<template>
<div>
<h2>toRaw与markRaw</h2>
<h3>state:{{state}}</h3>
<button @click="updateToRaw">测试toRaw</button>
<button @click="updateMarkRaw">测试markRaw</button>
</div>
</template>
<script lang="ts">
import { computed, defineComponent,reactive,ref,toRaw,markRaw } from 'vue'
interface UserInfo {
name:string,
age:number,
likes?:string[]
}
// 引入子集组件
import Child from './components/child.vue';
export default defineComponent({
components:{
Child
},
setup(){
const state = reactive<UserInfo>({
name:'小明',
age:12,
})
const updateToRaw = () => {
const user = toRaw(state)
user.name += '-----'
console.log('测试')
}
const updateMarkRaw = () => {
// state.likes = ['吃','喝']
// state.likes[0] += '-----'
const likes = ['吃','喝']
state.likes = markRaw(likes)
setInterval(() => {
console.log('定时器走起来')
if (state.likes) {
state.likes[0] += '----'
}
},1000)
console.log('测试')
}
return {
updateToRaw,
updateMarkRaw,
state
}
}
})
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
nav {
padding: 30px;
}
nav a {
font-weight: bold;
color: #2c3e50;
}
nav a.router-link-exact-active {
color: #42b983;
}
</style>
更多推荐
所有评论(0)