Demo12.vue 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <template>
  2. <div>
  3. <h3>这是第十二个demo:watch:监听ref、reactive:引用数据类型中的某个属性</h3>
  4. <p>我叫{{person.name}},今年{{person.age}}岁</p>
  5. <p>我会{{person.weapon.weapon2}},我有{{person.weapon.weapon1}}</p>
  6. <button @click="changeName">修改名字</button>
  7. <button @click="changeAge">修改年龄</button>
  8. <button @click="changeWeapon1">修改第一个</button>
  9. <button @click="changeWeapon2">修改第二个</button>
  10. <button @click="changeAll">修改整个武器</button>
  11. </div>
  12. </template>
  13. <script setup>
  14. import { watch, reactive} from 'vue'
  15. let person = reactive({
  16. name:"孙悟空",
  17. age:20,
  18. weapon:{
  19. weapon1:"金箍棒",
  20. weapon2:"七十二变"
  21. }
  22. })
  23. function changeName() {
  24. person.name = '猪八戒'
  25. }
  26. function changeAge() {
  27. person.age = 40
  28. }
  29. function changeWeapon1() {
  30. person.weapon.weapon1 = '九齿钉耙'
  31. }
  32. function changeWeapon2() {
  33. person.weapon.weapon2 = '三十六变'
  34. }
  35. function changeAll() {
  36. person.weapon = {
  37. weapon1:"画画",
  38. weapon2:"哈哈哈"
  39. }
  40. }
  41. // 监听多个响应式对象的某个属性 并且改属性是基本数据类型时 要写成函数式
  42. watch([()=>person.name,()=>person.age],(newValue,oldValue) => {
  43. console.log('改变了',newValue,oldValue)
  44. })
  45. </script>
  46. <style lang='scss' scoped>
  47. </style>