---
# System prepended metadata

title: Computed練習

---

### ==1.get 和 set用法==
```javascript=
<button type="button" @click="count += 1">{{ count }}, {{ plusOne }}</button>

const count = ref(1)
const plusOne = computed({
  get: () => count.value+1,
  set(val) {
    console.log(val)
  }
})
```


### ==2. Option 改成 Composition==
```javascript=
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.2.37/vue.global.js"></script>
  </head>
  <body>
    <div id="app">
      <button type="button" @click="sortBtn = !sortBtn">
        升降冪 {{ sortBtn }}
      </button>
      <span>排序項目: {{ sortText }} </span>
      <table>
        <thead>
          <tr>
            <th>姓名</th>
            <th @click="sortText = 'age'">年齡</th>
            <th>喜好</th>
            <th @click="sortText = 'price'">價格</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in sortPeople" :key="item.name">
            <td>{{ item.name }}</td>
            <td>{{ item.age }}</td>
            <td>{{ item.like }}</td>
            <td>{{ item.price }}</td>
          </tr>
        </tbody>
      </table>
    </div>
    <script>
      const app = Vue.createApp({
        data() {
          return {
            people: [
              {
                name: "卡斯伯",
                age: 20,
                like: "鍋燒意麵",
                price: 95,
              },
              {
                name: "瑞",
                age: 16,
                like: "炒麵",
                price: 80,
              },
              {
                name: "小明",
                age: 32,
                like: "黑胡椒燴飯",
                price: 120,
              },
              {
                name: "喬伊",
                age: 25,
                like: "生菜沙拉",
                price: 80,
              },
            ],
            sortBtn: true,
            sortText: "price",
          };
        },
        computed: {
          sortPeople() {
            return this.sortBtn
              ? this.people.sort((a, b) => a[this.sortText] - b[this.sortText])
              : this.people.sort((a, b) => b[this.sortText] - a[this.sortText]);
          },
        },
      });
      app.mount("#app");
    </script>
  </body>
</html>
```





