จริงๆแล้ว v-if กับ v-show เป็น vue.js directive ที่มีความสามารถใกล้เคียงกันมาก แต่จะมีบางจุดเท่านั้นที่แตกต่างกัน
สิ่งที่เหมือนกันคือ เป็นการตรวจสอบเงื่อนไขเหมือนกัน
สิ่งที่แตกต่างกันคือ v-if มันจะ render DOM ใหม่ทุกครั้งเมื่อมีการ toggle ถ้าไม่เข้าเงื่อนไข element นั้นก็จะถูกลบออกจาก DOM เช่น

ไฟล์ html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Project #2</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<h1>header</h1>
<section id="vueSection">
<p v-if="hiText">{{ greeting }}</p>
<button @click="toggleText()">Toggle Text</button>
</section>
<script src="app.js"></script>
</body>
</html>
ไฟล์ app.js
const app = Vue.createApp({
data() {
return {
greeting: 'Hi',
hiText: false,
}
},
methods: {
toggleText() {
this.hiText = !this.hiText;
}
}
});
app.mount('#vueSection');
ส่วน v-show จะ render DOM ไว้ในตอนเริ่มต้นเลย เมื่อมีการ toggle จะเปลี่ยน CSS Property ซึ่งก็คือ property display เป็นค่า none เมื่อไม่เข้าเงื่อนไข เช่น

ไฟล์ html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Project #2</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<h1>header</h1>
<section id="vueSection">
<p v-show="hiText">{{ greeting }}</p>
<button @click="toggleText()">Toggle Text</button>
</section>
<script src="app.js"></script>
</body>
</html>
ไฟล์ app.js ใช้เหมือนกันกับตัวบนครับ
แต่ไม่แนะนำให้ใช้ 2 ตัวนี้ร่วมกันนะจ๊ะ
command line ตรวจสอบ spec ใน Windows OS
วิธีผูก วินิจฉัย (Diagnosis) กับ วัคซีน (Vaccine)
ETL ใน Data Engineering คืออะไร?
แก้ปัญหา export ภาษาไทยเพี้ยน ของ MySQL ใน phpMyAdmin
เชื่อมตารางตัวเองใน MySQL ด้วย SELF JOIN
เคล็ดลับเพิ่มประสิทธิภาพการใช้ Google Docs
เทคนิคการใช้ ChatGPT Plus ให้คุ้มค่า คุ้มราคา
เชื่อมหลายฐานข้อมูล MySQL ใน Codeigniter4