1. <template>
    2. <div>
    3. <h2>{{person.name}}</h2>
    4. <h2 v-show='person.age'>{{person.age}}</h2>
    5. <h2>{{person.sex}}</h2>
    6. <h2>{{person.address}}</h2>
    7. <button @click='changeName'>修改姓名</button>
    8. <button @click='changeAge'>修改年龄</button>
    9. <button @click='addAdress'>添加地址</button>
    10. <button @click='deleteAge'>删除年龄</button>
    11. <hr>
    12. <ul>
    13. <li v-for="(item, index) in hobby" :key="index">
    14. {{ item }}
    15. </li>
    16. </ul>
    17. <button @click='addHobby'>添加hobby</button>
    18. <button @click='updateHobby'>修改hobby</button>
    19. </div>
    20. </template>
    21. <script>
    22. import { reactive} from'vue'
    23. export default {
    24. setup() {
    25. const person = reactive({
    26. name:'张三',
    27. age:20,
    28. sex:'女'
    29. })
    30. function changeName(){
    31. person.name += '!'
    32. }
    33. function changeAge(){
    34. person.age ++
    35. }
    36. function addAdress(){
    37. person.address = '陕西省'
    38. }
    39. function deleteAge(){
    40. delete person.age
    41. }
    42. const hobby = reactive(['画画','游泳'])
    43. function addHobby(){
    44. hobby.push('唱歌')
    45. }
    46. function updateHobby(){
    47. hobby[0] = '烫头'
    48. }
    49. return { person, changeName,changeAge, addAdress, deleteAge, hobby, addHobby, updateHobby }
    50. },
    51. }
    52. </script>

    原理:

    1. <script>
    2. const person = {
    3. name: '张三',
    4. age: 20
    5. }
    6. const p = new Proxy(person, {
    7. get(target, propName) {
    8. console.log('有人读取了属性')
    9. console.log(target, propName)
    10. return target, propName
    11. },
    12. //新增属性或者修改属性时调用
    13. set(target, propName, value) {
    14. console.log('有人修改了值')
    15. target[propName] = value
    16. },
    17. deleteProperty(target, propName){
    18. console.log('有人删除了属性')
    19. return delete target[propName]
    20. }
    21. })
    22. </script>
    1. //真正的vue3实现响应式
    2. <script>
    3. const person = {
    4. name: '张三',
    5. age: 20
    6. }
    7. const p = new Proxy(person, {
    8. get(target, propName) {
    9. console.log('有人读取了属性')
    10. console.log(target, propName)
    11. // return target, propName
    12. return Reflect.get(target, propName)
    13. },
    14. //新增属性或者修改属性时调用
    15. set(target, propName, value) {
    16. console.log('有人修改了值')
    17. // target[propName] = value
    18. Reflect.set(target, propName, value)
    19. },
    20. deleteProperty(target, propName){
    21. console.log('有人删除了属性')
    22. // return delete target[propName]
    23. return Reflect.defineProperty(target, propName)
    24. }
    25. })
    26. </script>

    总结:

    关于代理与反射,可以看这篇博文
    模拟Vue3中实现响应式