การใช้งาน ref
การใช้งาน ref
ใน Vue
ref
ใน VueVue Composition API มีฟังก์ชัน ref
ที่ใช้สำหรับสร้างและจัดการสถานะ (state) ที่สามารถเป็น reactive ภายในคอมโพเนนต์ของ Vue ได้
การประกาศ ref
ref
import { ref } from 'vue';
export default {
setup() {
const count = ref(0);
function increment() {
count.value++;
}
return {
count,
increment
};
}
};
การเข้าถึงค่าใน ref
ref
ค่าที่เก็บใน ref
จะต้องเข้าถึงด้วยการอ้างอิง .value
เช่น
console.log(count.value); // แสดงค่า count
การใช้งานใน Template
ใน Vue template คุณสามารถใช้งานได้โดยไม่ต้องอ้างอิง .value
<template>
<div>
<p>{{ count }}</p>
<button @click="increment">เพิ่ม</button>
</div>
</template>
สรุป
ref
ใช้เพื่อทำให้ค่าต่าง ๆ reactiveเข้าถึงค่าใน
ref
นอก template ด้วย.value
อ้างอิง
Last updated
Was this helpful?