computed用法

计算属性就是当依赖的属性的值发生变化的时候,才会触发他的更改,如果依赖的值,不发生变化的时候,使用的是缓存中的属性值。

1、函数形式

  1. import { computed, reactive, ref } from 'vue'
  2. let price = ref(0)//$0
  3. let m = computed<string>(()=>{
  4. return `$` + price.value
  5. })
  6. price.value = 500

2、 对象形式

  1. <template>
  2. <div>{{ mul }}</div>
  3. <div @click="mul = 100">click</div>
  4. </template>
  5. <script setup lang="ts">
  6. import { computed, ref } from 'vue'
  7. let price = ref<number | string>(1)//$0
  8. let mul = computed({
  9. get: () => {
  10. return price.value
  11. },
  12. set: (value) => {
  13. price.value = 'set' + value
  14. }
  15. })
  16. </script>
  17. <style>
  18. </style>

computed购物车案例

  1. <template>
  2. <div>
  3. <table style="width:800px" border>
  4. <thead>
  5. <tr>
  6. <th>名称</th>
  7. <th>数量</th>
  8. <th>价格</th>
  9. <th>操作</th>
  10. </tr>
  11. </thead>
  12. <tbody>
  13. <tr :key="index" v-for="(item, index) in data">
  14. <td align="center">{{ item.name }}</td>
  15. <td align="center">
  16. <button @click="AddAnbSub(item, false)">-</button>
  17. {{ item.num }}
  18. <button @click="AddAnbSub(item, true)">+</button>
  19. </td>
  20. <td align="center">{{ item.num * item.price }}</td>
  21. <td align="center">
  22. <button @click="del(index)">删除</button>
  23. </td>
  24. </tr>
  25. </tbody>
  26. <tfoot>
  27. <tr>
  28. <td></td>
  29. <td></td>
  30. <td></td>
  31. <td align="center">总价:{{ $total }}</td>
  32. </tr>
  33. </tfoot>
  34. </table>
  35. </div>
  36. </template>
  37. <script setup lang="ts">
  38. import { computed, reactive, ref } from 'vue'
  39. type Shop = {
  40. name: string,
  41. num: number,
  42. price: number
  43. }
  44. let $total = ref<number>(0)
  45. const data = reactive<Shop[]>([
  46. {
  47. name: "小满的袜子",
  48. num: 1,
  49. price: 100
  50. },
  51. {
  52. name: "小满的裤子",
  53. num: 1,
  54. price: 200
  55. },
  56. {
  57. name: "小满的衣服",
  58. num: 1,
  59. price: 300
  60. },
  61. {
  62. name: "小满的毛巾",
  63. num: 1,
  64. price: 400
  65. }
  66. ])
  67. const AddAnbSub = (item: Shop, type: boolean = false): void => {
  68. if (item.num > 1 && !type) {
  69. item.num--
  70. }
  71. if (item.num <= 99 && type) {
  72. item.num++
  73. }
  74. }
  75. const del = (index: number) => {
  76. data.splice(index, 1)
  77. }
  78. $total = computed<number>(() => {
  79. return data.reduce((prev, next) => {
  80. return prev + (next.num * next.price)
  81. }, 0)
  82. })
  83. </script>
  84. <style>
  85. </style>