← Back to Vue.js Course | Chapter 4: Components | Lesson 1 of 7

Components बनाना

एक component अपने template, data, और logic वाला एक reusable custom element है।
Syntax
markup
const app = Vue.createApp({});
app.component('component-name', {
  template: '<div>{{ message }}</div>',
  data() { return { message: 'text' }; }
});

<component-name></component-name>

Components बनाना

app.component(name, definition) से एक component register करें और इसे एक HTML tag की तरह इस्तेमाल करें। हर usage एक independent instance है। Components आपको interface को छोटे, testable, reusable pieces में split करने देते हैं।

Note: Native HTML elements से clash से बचने के लिए multi-word names इस्तेमाल करें।

उदाहरण: Creating components

markup
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
  <hello-card></hello-card>
  <hello-card></hello-card>
</div>
<script>
  const app = Vue.createApp({});
  app.component("hello-card", {
    data() { return { likes: 0 }; },
    template: '<div style="border:1px solid #ccc;padding:6px;margin:4px"><b>Hello!</b> <button @click="likes++">Like {{ likes }}</button></div>',
  });
  app.mount("#app");
</script>
</body>
</html>

<!-- Output:
Rendered: Hello! Like 0Hello! Like 0
-->
Live Example
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. HTML से clash करने वाले single-word names इस्तेमाल करना
  2. component register करना भूल जाना
  3. एक non-function data के जरिए accidentally state share करना
चैप्टर सारांश
  • app.component एक component register करता है
  • इसे एक custom tag की तरह इस्तेमाल करें
  • हर instance independent है
  • Multi-word names इस्तेमाल करें
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.