Mixins เป็นวิธีที่ช่วยในการแชร์โค้ดระหว่าง component เมื่อระบบเริ่มมีขนาดใหญ่ (sharable/reusable) โดย Mixin object สามารถมี component options ต่างๆ ผสมกันได้ (mixed) ไม่ว่าจะเป็น mounted, created, update และอื่นๆ เพื่อหลีกเลี่ยงการใช้ props มากเกินไปทำให้โค้ดรกและเกิดความสับสนได้ ลองดูตัวอย่างกันเลย
ไฟล์ mixin.js
export default {
data () {
message: 'Hello World'
},
created: function () {
console.log('Print from Mixin')
},
methods: {
showMessage: function () {
console.log('Print from mixin method')
}
}
}
ไฟล์ main.js
import mixin from './mixin.js'
new Vue({
mixins: [mixin],
created: function () {
console.log(this.$data)
console.log('Print from main.js file')
this.showMessage()
}
})
จากไฟล์ main.js ที่เรียก mixin.js มาใช้ จะเห็นได้ว่าเราสามารถ access ข้อมูลทุกอย่างในไฟล์ mixin.js ได้ ด้วยการใช้ this ซึ่งจะได้ผลลัพธ์ดังนี้
"Print from Mixin"
{message: 'Hello World'}
"Print from main.js file"
"Print from mixin method"
แล้วถ้าชื่อซ้ำกันจะทำยังไง?
ถ้ามีชื่อซ้ำกันระหว่าง component กับ mixin นั้นอะไรจะเกิดขึ้น? ผู้ที่ได้สิทธิในการใช้ชื่อนั้นคือ property ของ component เช่น
ไฟล์ mixin2.js
export default {
data () {
title: 'Mixin'
}
}
ไฟล์ main2.js
import mixin from ?./mixin.js?
export default {
mixins: [mixin],
data () {
title: 'Component'
},
created: function () {
console.log(this.title)
}
}
ผลลัพ์ที่ได้ คือ
"Component"
ขอบคุณข้อมูลจาก : levelup.gitconnected.com, vuejs.org
command line ตรวจสอบ spec ใน Windows OS
วิธีผูก วินิจฉัย (Diagnosis) กับ วัคซีน (Vaccine)
ETL ใน Data Engineering คืออะไร?
แก้ปัญหา export ภาษาไทยเพี้ยน ของ MySQL ใน phpMyAdmin
เชื่อมตารางตัวเองใน MySQL ด้วย SELF JOIN
เคล็ดลับเพิ่มประสิทธิภาพการใช้ Google Docs
เทคนิคการใช้ ChatGPT Plus ให้คุ้มค่า คุ้มราคา
เชื่อมหลายฐานข้อมูล MySQL ใน Codeigniter4