vue3 -- Class 对象在组件中使用范例

Published: · LastMod: April 07, 2024 · 165 words

vue3 – Class 对象在组件中使用范例 🔗

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<script setup>
import { ref, reactive } from "vue";

class FooItem {
  constructor() {
    this.a = 0;
  }
  increase(item) {
    item.a += 1;
    console.log(item);
  }
}

class Foo {
  constructor() {
    this.a = 1;
    this.list = [];
  }

  increase() {
    this.a += 1;
  }
  add(item) {
    this.list.splice(0, 0, item);
  }
}

const count = ref(new Foo());
const onClick = () => {
  count.value.increase();
};
const onAdd = () => {
  count.value.add(new FooItem());
};
</script>

<template>
  <div v-for="i in count.list">
    {{ i.a }} <button @click="i.increase(i)">inc</button>
  </div>
  <button @click="onClick">Count is: {{ count.a }}</button>
  <button @click="onAdd">add</button>
</template>

<style scoped>
button {
  font-weight: bold;
}
</style>