ตัวอย่างการใช้ Computed Property ใน VueJs

ตัวอย่างการใช้ Computed Property ใน VueJs

ใน VueJs computed properties เป็นฟังก์ชันที่กำหนดอยู่ใน computed ใน Vue component

Computed properties ช่วยให้เรา declare function ที่ return ค่า และค่านั้นจะถูก cache based on dependencies หมายความว่า computed property จะถูก re-evaluate ใหม่เมื่อหนึ่งใน dependencies เปลี่ยนแปลง

ตัวอย่างโค้ด

Vue.component('my-component', {
  data: {
    firstName: 'John',
    lastName: 'Doe'
  },
  computed: {
    fullName: function() {
      return this.firstName + ' ' + this.lastName;
    }
  }
});

จากตัวอย่างเรากำหนด computed property ที่ชื่อว่า fullName เป็นค่าที่เชื่อมระหว่าง firstName กับ lastName เมื่อใดก็ตามที่ firstName หรือ lastName เกิดการเปลี่ยนแปลง ค่า fullName จะถูกคำนวณใหม่

ตัวอย่างการนำไปใช้

<template>
  <div>
    <p>First name: {{ firstName }}</p>
    <p>Last name: {{ lastName }}</p>
    <p>Full name: {{ fullName }}</p>
  </div>
</template>

ตัวอย่างอื่น ๆ

<script setup>
import { ref, computed } from 'vue'

let id = 0

const newTodo = ref('')
const hideCompleted = ref(false)
const todos = ref([
  { id: id++, text: 'Learn HTML', done: true },
  { id: id++, text: 'Learn JavaScript', done: true },
  { id: id++, text: 'Learn Vue', done: false }
])

const filteredTodos = computed(() => {
  return hideCompleted.value
    ? todos.value.filter((t) => !t.done)
    : todos.value
})

function addTodo() {
  todos.value.push({ id: id++, text: newTodo.value, done: false })
  newTodo.value = ''
}

function removeTodo(todo) {
  todos.value = todos.value.filter((t) => t !== todo)
}
</script>

<template>
  <form @submit.prevent="addTodo">
    <input v-model="newTodo">
    <button>Add Todo</button>
  </form>
  <ul>
    <li v-for="todo in filteredTodos" :key="todo.id">
      <input type="checkbox" v-model="todo.done">
      <span :class="{ done: todo.done }">{{ todo.text }}</span>
      <button @click="removeTodo(todo)">X</button>
    </li>
  </ul>
  <button @click="hideCompleted = !hideCompleted">
    {{ hideCompleted ? 'Show all' : 'Hide completed' }}
  </button>
</template>

<style>
.done {
  text-decoration: line-through;
}
</style>


Copyright © 2023 Devcode Code Example - Powered by www.doesystem.com