Components
วิธีเขียน component, props, data, methods, child component และ instance context
Component ของ WebX คือ object ที่ export default จาก app.js และผูกกับ markup ใน template.html
import z from 'zod'
export default {
template: 'Counter',
props: {
title: z.string()
},
data: {
count: 0
},
method: {
increment() {
this.data.count++
}
}
}template
template คือชื่อ component tag ที่ parent ใช้เรียก
export default {
template: 'Counter'
}<Counter title="Static title" />
<Counter :title="name" />data
data เป็น state ภายใน component และถูก wrap ด้วย Proxy
export default {
data: {
name: 'WebX Component',
count: 0
}
}ใน template เข้าถึงได้ตรง ๆ:
<h1>{{ name }}</h1>
<p>{{ count }}</p>สามารถใช้ data เป็น function ได้หากต้องการสร้าง object ใหม่ต่อ instance:
export default {
data() {
return {
count: 0
}
}
}method และ methods
WebX รองรับทั้ง method และ methods โดย runtime จะ bind this ให้เป็น instance
export default {
method: {
increment() {
this.data.count++
},
reset() {
this.data.count = 0
}
}
}เรียกใน template ด้วย action directive:
<button @click="increment">Increment</button>
<button @click="reset()">Reset</button>Instance Context
ใน method, watcher และ lifecycle สามารถใช้ property เหล่านี้ผ่าน this
this.datareactive datathis.propsreactive propsthis.refselement refs จาก:refthis.cfxnamespace สำหรับ NUI callthis.watch(path, callback)เพิ่ม watcher runtimethis.<storeAlias>store ที่ bind จากstoresthis.methodsmethod ที่ bind แล้ว
Child Components
เพิ่ม component ลูกใน webx.json
{
"main": "home",
"components": ["counter"]
}ใน component ลูกกำหนด template name:
export default {
template: 'Counter'
}จากนั้น parent เรียกใช้ได้เหมือน HTML tag:
<Counter :title="name" />เมื่อ prop ที่ bind ด้วย : เปลี่ยน runtime จะอัปเดต childInstance.props และ trigger watcher ของ prop นั้น
Example
import z from 'zod'
import { useAppStore } from '@stores/appStore.js'
export default {
template: 'Counter',
stores: {
app: useAppStore
},
props: {
title: z.string()
},
data: {
count: 0
},
method: {
increment() {
this.data.count++
},
incrementShared() {
this.app.incrementSharedCount()
}
}
}