دليل مستخدم Vue.js

نسخة التطبيق (Application Instance)

يبدأ كل تطبيق Vue بإنشاء نسخة تطبيق جديدة باستخدام دالة createApp:

import { createApp } from 'vue'

const app = createApp({
  /* root component options */
})

المكوّن الجذر (Root Component)

الكائن المُمرَّر إلى createApp هو مكوّن. يتطلب كل تطبيق "مكوّنًا جذريًا" يمكنه احتواء مكوّنات أخرى كأبناء له.

تركيب التطبيق (Mounting the App)

لن تعرض نسخة التطبيق أي شيء حتى يتم استدعاء طريقة .mount() الخاصة بها:

app.mount('#app')

تهيئات التطبيق (App Configurations)

تعرض نسخة التطبيق كائن .config للتهيئة على مستوى التطبيق:

// App-level error handler
app.config.errorHandler = (err) => {
  /* handle error */
}

// Register global component
app.component('TodoDeleteButton', TodoDeleteButton)

نسخ تطبيق متعددة

يمكنك إنشاء تطبيقات Vue متعددة على نفس الصفحة:

const app1 = createApp({ /* ... */ })
app1.mount('#container-1')

const app2 = createApp({ /* ... */ })
app2.mount('#container-2')

صيغة القوالب (Template Syntax)

يستخدم Vue صيغة قوالب قائمة على HTML تتيح لك ربط DOM المعروض بشكل تصريحي ببيانات نسخة المكوّن الأساسية.

إدراج النص (Text Interpolation)

أبسط شكل لربط البيانات يستخدم صيغة "Mustache" (الأقواس المتعرجة المزدوجة):

<span>Message: {{ msg }}</span>

HTML الخام (Raw HTML)

استخدم التوجيه v-html لإخراج HTML حقيقي:

<p v-html="rawHtml"></p>

تحذير أمني: قد يؤدي عرض HTML عشوائي ديناميكيًا إلى ثغرات XSS. استخدم v-html فقط على المحتوى الموثوق وليس أبدًا على محتوى يوفّره المستخدم.

ربط السمات (Attribute Bindings)

استخدم التوجيه v-bind لربط سمات HTML:

<!-- Full syntax -->
<div v-bind:id="dynamicId"></div>

<!-- Shorthand -->
<div :id="dynamicId"></div>

<!-- Same-name shorthand (Vue 3.4+) -->
<div :id></div>

السمات المنطقية (Boolean Attributes)

تُضمَّن السمات المنطقية عندما تكون القيمة المربوطة صحيحة (truthy):

<button :disabled="isButtonDisabled">Button</button>

ربط سمات متعددة ديناميكيًا

اربط سمات متعددة من كائن باستخدام v-bind بدون وسيط:

const objectOfAttrs = {
  id: 'container',
  class: 'wrapper'
}
<div v-bind="objectOfAttrs"></div>

تعبيرات JavaScript

يدعم Vue تعبيرات JavaScript كاملة في جميع عمليات ربط البيانات:

{{ number + 1 }}
{{ ok ? 'YES' : 'NO' }}
{{ message.split('').reverse().join('') }}
<div :id="`list-${id}`"></div>

استدعاء الدوال

استدعِ الطرق المُتاحة من المكوّن في تعبيرات الربط:

<time :title="toTitleDate(date)" :datetime="date">
  {{ formatDate(date) }}
</time>

الوصول المقيّد إلى المتغيرات العامة

ليس لتعبيرات القوالب وصول إلا إلى قائمة مقيّدة من المتغيرات العامة (Math، Date، إلخ). أضف متغيرات عامة إضافية عبر app.config.globalProperties.

التوجيهات (Directives)

التوجيهات هي سمات خاصة بالبادئة v-.

الوسائط (Arguments)

تأخذ بعض التوجيهات وسائط يُشار إليها بنقطتين رأسيتين:

<!-- 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>

الوسائط الديناميكية (Dynamic Arguments)

استخدم تعبيرات JavaScript في وسائط التوجيهات باستخدام الأقواس المربعة:

<a :[attributeName]="url"> ... </a>
<a @[eventName]="doSomething"> ... </a>

القيود:

  • يجب أن تُقيَّم الوسائط الديناميكية إلى سلسلة نصية أو null
  • تجنّب التعبيرات المعقدة؛ استخدم الخصائص المحسوبة (computed properties) بدلاً منها
  • في قوالب DOM، تجنّب الأحرف الكبيرة في المفاتيح الديناميكية

المُعدِّلات (Modifiers)

المُعدِّلات هي لواحق خاصة يُشار إليها بنقطة:

<form @submit.prevent="onSubmit">...</form>

أساسيات التفاعلية (Reactivity Fundamentals)

تعريف الحالة التفاعلية

أنشئ مراجع تفاعلية باستخدام ref():

import { ref } from 'vue'

const count = ref(0)
console.log(count.value) // 0

count.value++
console.log(count.value) // 1

الكائنات التفاعلية

أنشئ كائنات تفاعلية باستخدام reactive():

import { reactive } from 'vue'

const state = reactive({
  count: 0
})

الخصائص المحسوبة (Computed Properties)

أنشئ خصائص محسوبة باستخدام 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'
})

المراقبون (Watchers)

راقب تغييرات البيانات التفاعلية باستخدام 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
    }
  }
})

أساسيات المكوّنات (Component Basics)

تعريف المكوّنات

// Define component
const Component = {
  data() {
    return {
      count: 0
    }
  },
  template: `<button @click="count++">Count is: {{ count }}</button>`
}

تمرير الخصائص (Passing Props)

// Child component
const Child = {
  props: ['msg'],
  template: `<div>{{ msg }}</div>`
}

// Parent component
const Parent = {
  components: { Child },
  template: `<Child msg="Hello!"></Child>`
}

إطلاق الأحداث (Emitting Events)

// Child component
const Child = {
  emits: ['response'],
  methods: {
    respond() {
      this.$emit('response', 'Hello from child!')
    }
  },
  template: `<button @click="respond">Respond</button>`
}

الفتحات (Slots)

<!-- 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>