Manual Pengguna Vue.js
Instans Aplikasi
Setiap aplikasi Vue bermula dengan mencipta instans aplikasi baharu menggunakan fungsi createApp:
import { createApp } from 'vue'
const app = createApp({
/* root component options */
})
Komponen Akar
Objek yang dihantar ke createApp ialah sebuah komponen. Setiap aplikasi memerlukan "komponen akar" yang boleh mengandungi komponen lain sebagai anaknya.
Memasang Aplikasi
Instans aplikasi tidak akan rendering apa-apa sehingga kaedah .mount() dipanggil:
app.mount('#app')
Konfigurasi Aplikasi
Instans aplikasi mendedahkan objek .config untuk konfigurasi peringkat aplikasi:
// App-level error handler
app.config.errorHandler = (err) => {
/* handle error */
}
// Register global component
app.component('TodoDeleteButton', TodoDeleteButton)
Instans Aplikasi Pelbagai
Anda boleh mencipta berbilang aplikasi Vue pada halaman yang sama:
const app1 = createApp({ /* ... */ })
app1.mount('#container-1')
const app2 = createApp({ /* ... */ })
app2.mount('#container-2')
Sintaks Templat
Vue menggunakan sintaks templat berasaskan HTML yang membolehkan anda mengikat DOM yang dirender secara deklaratif kepada data instans komponen yang asas.
Interpolasi Teks
Bentuk paling asas ikatan data menggunakan sintaks "Mustache" (kurungan keriting berganda):
<span>Message: {{ msg }}</span>
HTML Mentah
Gunakan arahan v-html untuk mengeluarkan HTML sebenar:
<p v-html="rawHtml"></p>
Amaran Keselamatan: Rendering HTML arbitri secara dinamik boleh menyebabkan kerentanan XSS. Gunakan v-html hanya pada kandungan yang dipercayai dan jangan pernah pada kandungan yang dibekalkan pengguna.
Ikatan Atribut
Gunakan arahan v-bind untuk mengikat atribut HTML:
<!-- Full syntax -->
<div v-bind:id="dynamicId"></div>
<!-- Shorthand -->
<div :id="dynamicId"></div>
<!-- Same-name shorthand (Vue 3.4+) -->
<div :id></div>
Atribut Boolean
Atribut boolean disertakan apabila nilai yang diikat itu bernilai benar:
<button :disabled="isButtonDisabled">Button</button>
Mengikat berbilang Atribut Dinamik
Ikat berbilang atribut daripada objek menggunakan v-bind tanpa argumen:
const objectOfAttrs = {
id: 'container',
class: 'wrapper'
}
<div v-bind="objectOfAttrs"></div>
Ekspresi JavaScript
Vue menyokong ekspresi JavaScript penuh dalam semua ikatan data:
{{ number + 1 }}
{{ ok ? 'YES' : 'NO' }}
{{ message.split('').reverse().join('') }}
<div :id="`list-${id}`"></div>
Memanggil Fungsi
Panggil kaedah yang didedahkan oleh komponen dalam ekspresi ikatan:
<time :title="toTitleDate(date)" :datetime="date">
{{ formatDate(date) }}
</time>
Akses Global Terhad
Ekspresi templat hanya mempunyai akses kepada senarai global yang terhad (Math, Date, dan lain-lain). Tambah global tambahan melalui app.config.globalProperties.
Arahan
Arahan ialah atribut khas dengan awalan v-.
Argumen
Sesetengah arahan mengambil argumen yang ditandakan dengan titik bertindih:
<!-- v-bind argument -->
<a v-bind:href="url"> ... </a>
<a :href="url"> ... </a>
<!-- v-on argument -->
<a v-on:click="doSomething"> ... </a>
<a @click="doSomething"> ... </a>
Argumen Dinamik
Gunakan ekspresi JavaScript dalam argumen arahan dengan kurungan segi empat:
<a :[attributeName]="url"> ... </a>
<a @[eventName]="doSomething"> ... </a>
Kekangan:
- Argumen dinamik mesti dinilai kepada rentetan atau null
- Elakkan ekspresi yang kompleks; gunakan sifat terkira sebaliknya
- Dalam templat DOM, elakkan aksara huruf besar dalam kunci dinamik
Pengubah
Pengubah ialah postfix khas yang ditandakan dengan titik:
<form @submit.prevent="onSubmit">...</form>
Asas Reaktivitas
Mengisytiharkan Keadaan Reaktif
Cipta rujukan reaktif dengan ref():
import { ref } from 'vue'
const count = ref(0)
console.log(count.value) // 0
count.value++
console.log(count.value) // 1
Objek Reaktif
Cipta objek reaktif dengan reactive():
import { reactive } from 'vue'
const state = reactive({
count: 0
})
Sifat Terkira
Cipta sifat terkira dengan computed():
import { ref, computed } from 'vue'
const author = ref({
name: 'John Doe',
books: [
'Vue 2 Guide',
'Vue 3 Guide',
'Vue Mastery'
]
})
const publishedBooksMessage = computed(() => {
return author.value.books.length > 0
? 'Yes'
: 'No'
})
Pemerhati
Perhati perubahan data reaktif dengan watch():
import { ref, watch } from 'vue'
const question = ref('')
const answer = ref('Questions usually contain a question mark. ;-)')
// Watch single ref
watch(question, async (newQuestion, oldQuestion) => {
if (newQuestion.indexOf('?') > -1) {
answer.value = 'Thinking...'
try {
const res = await fetch('https://yesno.wtf/api')
answer.value = (await res.json()).answer
} catch (error) {
answer.value = 'Error! Could not reach the API. ' + error
}
}
})
Asas Komponen
Mendefinisikan Komponen
// Define component
const Component = {
data() {
return {
count: 0
}
},
template: `<button @click="count++">Count is: {{ count }}</button>`
}
Menghantar Props
// Child component
const Child = {
props: ['msg'],
template: `<div>{{ msg }}</div>`
}
// Parent component
const Parent = {
components: { Child },
template: `<Child msg="Hello!"></Child>`
}
Memancarkan Peristiwa
// Child component
const Child = {
emits: ['response'],
methods: {
respond() {
this.$emit('response', 'Hello from child!')
}
},
template: `<button @click="respond">Respond</button>`
}
Slot
<!-- Child component -->
<template>
<div>
<slot></slot>
<slot name="footer"></slot>
</div>
</template>
<!-- Parent component -->
<Child>
<p>This is default slot content</p>
<template #footer>
<p>This is footer slot content</p>
</template>
</Child>
