فهرست سرفصل‌های Vue
خانه (HOME) معرفی (Intro) دایرکتیوها (Directives) v-bind (v-bind) v-if (v-if) v-show (v-show) v-for (v-for) رویدادها (Events) v-on (v-on) متدها (Methods) تغییردهنده های رویداد (Event Modifiers) فرم ها (Forms) v-model (v-model) بایندینگ CSS (CSS Binding) ویژگی های محاسبه شده (Computed Properties) واچرها (Watchers) قالب ها (Templates) چرا، چگونه و راه اندازی (Why, How and Setup) اولین صفحه SFC (First SFC Page) کامپوننت ها (Components) پراپس (Props) کامپوننت های v-for (v-for Components) $emit() ($emit()) ویژگی های عبوری (Fallthrough) (Fallthrough Attributes) استایل Scoped (Scoped Styling) کامپوننت های محلی (Local Components) اسلات ها (Slots) v-slot (v-slot) اسلات های Scoped (Scoped Slots) کامپوننت های پویا (Dynamic Components) Teleport (Teleport) درخواست HTTP (HTTP Request) رفرنس های تمپلیت (Template Refs) هوک های چرخه عمر (Lifecycle Hooks) Provide/Inject (Provide/Inject) مسیریابی (Routing) ورودی های فرم (Form Inputs) انیمیشن ها (Animations) انیمیشن با v-for (Animations with v-for) بیلد (Build) Composition API (Composition API) ویژگی های توکار (Built-in Attributes) ویژگی 'is' ('is' Attribute) ویژگی 'key' ('key' Attribute) ویژگی 'ref' ('ref' Attribute) کامپوننت های توکار (Built-in Components) <KeepAlive> (<KeepAlive>) <Teleport> (<Teleport>) <Transition> (<Transition>) <TransitionGroup> (<TransitionGroup>) المان های توکار (Built-in Elements) <component> (<component>) <slot> (<slot>) <template> (<template>) نمونه کامپوننت (Component Instance) $attrs ($attrs) $data ($data) $el ($el) $parent ($parent) $props ($props) $refs ($refs) $root ($root) $slots ($slots) $emit() ($emit()) $forceUpdate() ($forceUpdate()) $nextTick() ($nextTick()) $watch() ($watch()) دایرکتیوها (Directives) v-bind (v-bind) v-cloak (v-cloak) v-for (v-for) v-html (v-html) v-if (v-if) v-else-if (v-else-if) v-else (v-else) v-memo (v-memo) v-model (v-model) v-on (v-on) v-once (v-once) v-pre (v-pre) v-show (v-show) v-slot (v-slot) v-text (v-text) گزینه های نمونه (Instance Options) داده ها (data) متدها (methods) محاسبه شده ها (computed) watch (watch) پراپس (props) emits (emits) expose (expose) هوک های چرخه عمر (Lifecycle Hooks) beforeCreate (beforeCreate) created (created) beforeMount (beforeMount) mounted (mounted) beforeUpdate (beforeUpdate) updated (updated) beforeUnmount (beforeUnmount) unmounted (unmounted) errorCaptured (errorCaptured) renderTracked (renderTracked) renderTriggered (renderTriggered) activated (activated) deactivated (deactivated) serverPrefetch (serverPrefetch) مثال ها (Examples) تمرین ها (Exercises) کوییز (Quiz) سیلابس (Syllabus) برنامه مطالعه (Study Plan) سرور (Server) گواهینامه (Certificate)
نتیجه‌ای برای جستجو یافت نشد.
Vue

Vue — هوک های چرخه عمر (Lifecycle Hooks)

آخرین بروزرسانی: 1404/08/21

هوک های چرخه عمر (Lifecycle Hooks)

«هوک چرخه عمر (Lifecycle Hook)» یعنی جای خاصی در زندگی یک کامپوننت که می توانیم کد اجرا کنیم. مثل زنگ شروع کلاس یا زنگ تفریح در مدرسه؛ هر زنگ، کاری دارد.

beforeCreate: قبل از ساخت کامپوننت

در هوک beforeCreate هنوز داده ها و متدها آماده نیستند. پس به data یا DOM دست نزن.

<template>
  <h2>Component</h2>
  <p>This is the component</p>
  <p id="pResult">{{ text }}</p>
</template>

<script>
export default {
  data() {
    return {
      text: "..."
    };
  },
  beforeCreate() {
    this.text = "initial text";
    console.log("beforeCreate: The component is not created yet.");
  }
};
<\/script>

مشاهده در ادیتور

<template>
  <h1>The 'beforeCreate' Lifecycle Hook</h1>
  <p>We can see the console.log() message from 'beforeCreate' lifecycle hook, but there is no effect from the text change we try to do to the Vue data property, because the Vue data property is not created yet.</p>
  <button @click="this.activeComp = !this.activeComp">Add/Remove Component</button>
  <div>
    <comp-one v-if="activeComp"></comp-one>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeComp: false
    };
  }
};
<\/script>

<style>
#app > div {
  border: dashed black 1px;
  border-radius: 10px;
  padding: 10px;
  margin-top: 10px;
  background-color: lightgreen;
}
#pResult {
  background-color: lightcoral;
  display: inline-block;
}
<\/style>

مشاهده در ادیتور

created: داده ها آماده می شوند

در created داده ها و متدها حاضرند. اما هنوز درخت DOM سوار نشده است.

<template>
  <h2>Component</h2>
  <p>This is the component</p>
  <p id="pResult">{{ text }}</p>
</template>

<script>
export default {
  data() {
    return {
      text: "..."
    };
  },
  created() {
    this.text = "initial text";
    console.log("created: The component just got created.");
  }
};
<\/script>

مشاهده در ادیتور

beforeMount: هنوز به DOM وصل نشده

در beforeMount عنصرهای DOM در دسترس نیستند. پس با ref کاری نکن.

<template>
  <h2>Component</h2>
  <p>This is the component</p>
  <p ref="pEl" id="pEl">We try to access this text from the 'beforeMount' hook.</p>
</template>

<script>
export default {
  beforeMount() {
    console.log("beforeMount: just before mount.");
    this.$refs.pEl.innerHTML = "Hello World!";
  }
};
<\/script>

مشاهده در ادیتور

mounted: بهترین زمان کار با DOM

در mounted کامپوننت داخل DOM است. اکنون می توانی با ref کار کنی.

<template>
  <h2>Form Component</h2>
  <p>When mounted, focus the input.</p>
  <form @submit.prevent>
    <label>
      <p>Name:<br><input type="text" ref="inpName"></p>
    </label>
    <label>
      <p>Age:<br><input type="number"></p>
    </label>
    <button>Submit</button>
  </form>
</template>

<script>
export default {
  mounted() {
    this.$refs.inpName.focus();
  }
};
<\/script>

مشاهده در ادیتور

beforeUpdate: قبل از رندرِ تغییرات

وقتی داده عوض می شود، قبل از رندر، beforeUpdate اجرا می شود. اینجا می توانی لاگ بنویسی.

<template>
  <h1>The 'beforeUpdate' Lifecycle Hook</h1>
  <p>Safe to modify logs here.</p>
  <button @click="this.activeComp = !this.activeComp">Add/Remove Component</button>
  <div>
    <comp-one v-if="activeComp"></comp-one>
  </div>
  <ol ref="divLog"></ol>
</template>

<script>
export default {
  data() {
    return {
      activeComp: true
    };
  },
  beforeUpdate() {
    this.$refs.divLog.innerHTML += "<li>beforeUpdate ran.</li>";
  }
};
<\/script>

<style>
#app > div {
  border: dashed black 1px;
  border-radius: 10px;
  padding: 10px;
  margin-top: 10px;
  background-color: lightgreen;
}
<\/style>

مشاهده در ادیتور

updated: بعد از رندرِ تغییرات

در updated صفحه دوباره رندر شده است. بنابراین محتاط باش و DOM را عوض نکن.

<template>
  <h1>The 'updated' Lifecycle Hook</h1>
  <p>Updating causes console.log here.</p>
  <button @click="this.activeComp = !this.activeComp">Add/Remove Component</button>
  <div>
    <comp-one v-if="activeComp"></comp-one>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeComp: true
    };
  },
  updated() {
    console.log("The component is updated!");
  }
};
<\/script>

مشاهده در ادیتور

هشدار: تغییر مستقیم صفحه در updated حلقه بی نهایت می سازد.

<template>
  <h1>The 'updated' Lifecycle Hook</h1>
  <p>This example triggers a loop.</p>
  <button @click="this.activeComp = !this.activeComp">Add/Remove Component</button>
  <div>
    <comp-one v-if="activeComp"></comp-one>
  </div>
  <div>{{ text }}</div>
</template>

<script>
export default {
  data() {
    return {
      activeComp: true,
      text: "Hello, "
    };
  },
  updated() {
    this.text += "hi, ";
  }
};
<\/script>

مشاهده در ادیتور

beforeUnmount و unmounted: خداحافظی با DOM

beforeUnmount درست قبلِ حذف اجرا می شود. unmounted بعد از حذف اجرا می شود.

<template>
  <h2>Component</h2>
  <p ref="pEl">Strawberries!</p>
</template>

<script>
export default {
  beforeUnmount() {
    alert("beforeUnmount: " + this.$refs.pEl.innerHTML);
  }
};
<\/script>

مشاهده در ادیتور

<template>
  <h2>Component</h2>
  <p>When unmounted, alert shows.</p>
</template>

<script>
export default {
  unmounted() {
    alert("The component is removed (unmounted)!");
  }
};
<\/script>

مشاهده در ادیتور

errorCaptured: خطای فرزند را بگیر

اگر در فرزند خطا شود، والد می تواند با errorCaptured آن را بگیرد و گزارش کند.

<template>
  <h1>The 'errorCaptured' Lifecycle Hook</h1>
  <div>
    <comp-one></comp-one>
  </div>
</template>

<script>
export default {
  errorCaptured() {
    alert("An error occurred");
  }
};
<\/script>

مشاهده در ادیتور

activated / deactivated: وقتی کش فعال است

با <KeepAlive> کامپوننت کش می شود. آنگاه activated و deactivated به جای حذف کامل، اجرا می شوند.

<template>
  <h1>The 'activated' Lifecycle Hook</h1>
  <p>Check caching with <KeepAlive>.</p>
  <button @click="this.activeComp = !this.activeComp">Include component</button>
  <div>
    <KeepAlive>
      <comp-one v-if="activeComp"></comp-one>
    </KeepAlive>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeComp: false
    };
  }
};
<\/script>

مشاهده در ادیتور

گام های عملی

  1. کارهای داده ای را در created انجام بده.
  2. کارهای DOM را در mounted انجام بده.
  3. در updated تغییر DOM نده.
  4. قبل حذف از beforeUnmount بهره ببر.

جمع بندی سریع

  • beforeCreate هنوز هیچ چیز آماده نیست.
  • created داده ها آماده اند، DOM نه.
  • mounted بهترین زمان کار با DOM است.
  • updated را فقط برای گزارش استفاده کن.
  • beforeUnmount و unmounted برای خداحافظی اند.