Demo.vue 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <template>
  2. <h4>当前求和为:{{sum}}</h4>
  3. <button @click="sum++">点我++</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+='~'">修改姓名</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.name+='!'">换车名</button>
  15. <button @click="changePrice">换价格</button>
  16. </template>
  17. <script>
  18. import {ref,reactive,toRefs,toRaw,markRaw} from 'vue'
  19. export default {
  20. name: 'Demo',
  21. setup(){
  22. //数据
  23. let sum = ref(0)
  24. let person = reactive({
  25. name:'张三',
  26. age:18,
  27. job:{
  28. j1:{
  29. salary:20
  30. }
  31. }
  32. })
  33. function showRawPerson(){
  34. const p = toRaw(person)
  35. p.age++
  36. console.log(p)
  37. }
  38. function addCar(){
  39. let car = {name:'奔驰',price:40}
  40. person.car = markRaw(car)
  41. }
  42. function changePrice(){
  43. person.car.price++
  44. console.log(person.car.price)
  45. }
  46. //返回一个对象(常用)
  47. return {
  48. sum,
  49. person,
  50. ...toRefs(person),
  51. showRawPerson,
  52. addCar,
  53. changePrice
  54. }
  55. }
  56. }
  57. </script>