|
| 1 | +<template> |
| 2 | + <h2>当前求和为:{{ sum }}</h2> |
| 3 | + <button @click="sum++">sum+1</button> |
| 4 | + <hr/> |
| 5 | + <h2>姓名:{{ name }}</h2> |
| 6 | + <h2>年龄:{{ age }}</h2> |
| 7 | + <h2>薪资:{{ job.j1.salary }}K</h2> |
| 8 | + <h3 v-show="person.car">座驾信息:{{ person.car }}</h3> |
| 9 | + <button @click="name = name + '~'">修改姓名</button> |
| 10 | + <button @click="age++">增长年龄</button> |
| 11 | + <button @click="job.j1.salary++">增长薪资</button> |
| 12 | + <button @click="showRawPerson">输出最原始的person</button> |
| 13 | + <button @click="addCar">给人添加一台车</button> |
| 14 | + <button @click="person.car && (person.car.name +='!') ">换车名</button> |
| 15 | + <button @click="changePrice">换价格</button> |
| 16 | +</template> |
| 17 | + |
| 18 | +<script> |
| 19 | +import {markRaw, reactive, ref, toRaw, toRefs} from 'vue'; |
| 20 | +
|
| 21 | +export default { |
| 22 | + name: 'Demo', |
| 23 | + setup(){ |
| 24 | +
|
| 25 | + let sum = ref(0); |
| 26 | +
|
| 27 | + let person = reactive({ |
| 28 | + name: '张三', |
| 29 | + age: 18, |
| 30 | + job:{ |
| 31 | + j1:{ |
| 32 | + salary: 20 |
| 33 | + } |
| 34 | + } |
| 35 | + }); |
| 36 | +
|
| 37 | + //ref reactive(响应式) |
| 38 | +
|
| 39 | + const showRawPerson = () => { |
| 40 | + const p = toRaw(person); |
| 41 | + // console.log(person); //proxy代理对象 Proxy {....} |
| 42 | + p.age++; //注意此时页面不会再发生变化了,普普通通的对象不是响应式 |
| 43 | + console.log(p); //原始对象数据 {....} |
| 44 | +
|
| 45 | + // const sum = toRaw(sum); |
| 46 | + // console.log(sum); //undefined //这条路走不通,toRaw只处理reactive对象 |
| 47 | + } |
| 48 | +
|
| 49 | + const addCar = () => { |
| 50 | + person.car = markRaw({ |
| 51 | + name: 'benz', |
| 52 | + price: 40 |
| 53 | + }); //在响应式的对象身上添加任何属性都是响应式的,经过markRaw一包装就变成最原始的数据就不会再做响应 |
| 54 | + } |
| 55 | +
|
| 56 | +
|
| 57 | + const changePrice = () => { |
| 58 | + person.car?.price && person.car.price++; |
| 59 | + console.log(person?.car?.price); |
| 60 | + } |
| 61 | +
|
| 62 | + return { |
| 63 | + sum, |
| 64 | + person, |
| 65 | + ...toRefs(person), |
| 66 | + showRawPerson, |
| 67 | + addCar, |
| 68 | + changePrice |
| 69 | + }; |
| 70 | +
|
| 71 | + } |
| 72 | +} |
| 73 | +</script> |
| 74 | +
|
| 75 | +<style> |
| 76 | +</style> |
| 77 | +
|
0 commit comments