App.vue 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <template>
  2. <h2> toRaw 与 markRaw</h2>
  3. <h3>state: {{ state }}</h3>
  4. <hr>
  5. <button @click="testToRaw">测试toRaw</button>
  6. <button @click="testMarkRow">测试markRaw</button>
  7. </template>
  8. <script lang="ts">
  9. import { defineComponent, markRaw, reactive, toRaw } from 'vue'
  10. interface userInfo{
  11. name: string,
  12. age: number,
  13. likes?: string[]
  14. }
  15. export default defineComponent({
  16. setup () {
  17. const state = reactive<userInfo>({
  18. name:'zs',
  19. age: 18
  20. })
  21. const testToRaw = ()=>{
  22. //把代理对象编程普通对象 数据变化 页面不变化
  23. const user = toRaw(state)
  24. user.name += '=='
  25. console.log(111)
  26. }
  27. const testMarkRow = ()=>{
  28. // state.likes = ['吃','喝']
  29. // state.likes[0] += '='
  30. // console.log(state)
  31. const likes = ['吃','喝']
  32. state.likes = markRaw(likes)
  33. //markRaw标记独享的数据,从此以后都不能成为代理对象了
  34. setInterval(()=>{
  35. if(state.likes){
  36. state.likes[0] += '='
  37. console.log('定时器启动')
  38. }
  39. },1000)
  40. }
  41. return {
  42. state,
  43. testToRaw,
  44. testMarkRow
  45. }
  46. }
  47. })
  48. </script>
  49. <style scoped>
  50. </style>