Location>code7788 >text

"Vue2 Framework Lesson 2: Detailed Explanation of Component Structure and Template Syntax"

Popularity:174 ℃/2025-02-14 23:16:14

Written at the beginning: It is a popular front-end framework, widely used in building user interfaces and single page applications (SPAs). However, it should be noted that Vue2 has officially stopped maintaining at the end of 2023. This means that the official team will no longer provide feature updates and security patches for Vue2.

Despite this, Vue2 still has a wide range of influence and usage scenarios in the industry. Many existing projects are still built on Vue2. Learning Vue2 not only helps us understand and maintain these legacy projects, but also lays a solid foundation for us to learn Vue3 later. Although Vue3 has introduced many new features and performance optimizations, its core concept is in line with Vue2. Therefore, mastering the basics of Vue2 is essential for a smooth transition to Vue3.

1. Introduction: Why is componentized development the core of Vue?

InComponent developmentIt is the core idea for building large-scale applications. Through components, we can split a complex page into independent, reusable modules. For example, the page of an e-commerce website can be split intoProduct Card ComponentsShopping cart componentsSearch bar componentetc. Each component is responsible for a specific function. This development model not only improves code reuse rate, but also makes collaborative development and post-maintenance more efficient.

If you haven't read my first lesson yet, it's recommended to review it first"The First Lesson of the First Introduction to Vue2 Framework: Basic Concepts and Environment Construction". Next, let's officially enter the world of Vue2 components!

This lesson will explain in depth the structure and template grammar of Vue2 components, and passComplete exampleHelp you fully grasp these core concepts.


2. Detailed explanation of Vue2 component structure

(I) Three core parts of the component

1. template: The skeleton of the component

  • effect: Define HTML structure and support Vue's template syntax (such as interpolation and instructions).

  • limit: There must be only one root element (such as outer layer<div>pack).

  • principle: Vue will compile the template into a virtual DOM to achieve efficient DOM updates.

  • Example

 <template>
   <div class="container">
     <h1>{{ title }}</h1>
   </div>
 </template>

2. script: The logic of the component

  • Data-driven:passdata()Function returns responsive data (Must be a function to avoid data contamination during component reuse)。

  • Method definition:existmethodsDefine event handling functions in

  • Life cycle hook:likecreated()mounted(), used to execute logic at a specific stage.

  • Example

<script>
 export default {
   data() {
     return { title: "Hello Vue2!" };
   },
   methods: {
     updateTitle() {
        = "Data has been updated!";
     }
   },
   mounted() {
     ("Component mounted!");
   }
 };
 </script>

3. style: Component style

  • Scope control:usescopedAttributes allow styles to only work on the current component (the principle is to add elementsdata-v-xxxattribute selector).

  • Preprocessor support: Can be matched<style lang="scss">Use Sass/Less.

  • Example

<style scoped>
.container {
  padding: 20px;
  background: #f0f0f0;
}
</style>

(II) Two ways to register components

1. Global registration

  • Applicable scenarios: Basic components of high-frequency multiplexing (such as buttons, input boxes).

  • Registration method

// 
import MyButton from './components/';
('MyButton', MyButton);
  • shortcoming: Globally registered components will increase the initial package volume.

2. Local registration

  • Applicable scenarios: Components that are only used in specific parent components.

  • Registration method

// 
import ChildComponent from './';
export default {
  components: { ChildComponent }
};

3. In-depth analysis of Vue2 template syntax

(I) Interpolation expression:{{ }}The mystery of

  • Basic usage<p>{{ message }}</p>

  • Expression support: Can write simple expressions, such as{{ count + 1 }}

  • Security Limitations: Automatically escape HTML content to prevent XSS attacks. If you need raw HTML, usev-htmlinstruction.

(II) Instructions: The Soul of Vue Template

1. Data binding

  • v-bind: Dynamic binding attribute, can be abbreviated as:
<img :src="imageUrl" :alt="imgAlt">

2. Event monitoring

  • v-on: Listen to DOM events, which can be abbreviated as@
<button @click="handleClick">Click</button>

3. Conditional Rendering

  • v-if vs v-show

  • v-if: Directly destroy/create elements, suitable for switching scenarios with low frequency.

  • v-show: Through CSSdisplayControl display, suitable for frequent switching.

4. List rendering

  • v-forMust match:key
<li v-for="item in items" :key="">{{  }}</li>

Why do you need a key?Help Vue update virtual DOM efficiently to avoid element misalignment

4. Practical example: a complete to-do component

<template>
   <div class="todo-list">
     <input
       v-model="newTodo"
       @="addTodo"
       placeholder="Press Enter after entering the task"
     >
     <ul>
       <li v-for="todo in todos" :key="">
         {{ }}
         <button @click="removeTodo()">×</button>
       </li>
     </ul>
     <p v-if=" === 0">No task yet, go and add it!  </p>
   </div>
 </template>

 <script>
 export default {
   data() {
     return {
       newTodo: '',
       todos: [
         { id: 1, text: 'learning Vue2 components' },
         { id: 2, text: 'Writing a technical blog' }
       ]
     };
   },
   methods: {
     addTodo() {
       if (()) {
         ({
           id: (),
           text:
         });
          = '';
       }
     },
     removeTodo(id) {
        = (todo => !== id);
     }
   }
 };
 </script>

 <style scoped>
 .todo-list {
   max-width: 400px;
   margin: 20px auto;
 }
 li {
   display: flex;
   justify-content: space-between;
   padding: 8px;
   border-bottom: 1px solid #eee;
 }
 </style>

Functional analysis:

  1. usev-modelImplement bidirectional binding of input boxes

  2. @Listen to the carriage return event

  3. v-forRendering list,:keyBind unique ID

  4. v-ifControl empty status prompt

5. Pit avoidance guide: FAQs and solutions

1. Why must data be a function?

Avoid multiple component instances sharing the same data object, resulting in state pollution.

2. v-forandv-ifPriority issues when using simultaneously

v-forThe priority is higher, so it is recommended to use calculation attributes to filter the data first.

3. Style conflict problem

usescopedProperties or CSS Modules isolate styles.

6. Summary

Through this article, you have mastered:

  • ✅ The three core structures of components

  • ✅ Key directives in template syntax

  • ✅ Best practices for component registration

  • ✅ Common pit avoidance techniques in actual development

In subsequent courses, we will combine Vuex state management and Vue Router routing to create more complex applications. It is recommended that readers implement the sample code hands-on and try to extend the functionality (such as adding task completion status).

Written at the end
hello! Hello everyone, I am Code_Cracke, a friend who loves programming. Here, I will share some practical development skills and experiences. If you are also passionate about programming, please follow and communicate and learn together!

If you have any questions, suggestions or unique insights about this article, please leave a message in the comment area. Whether it is exploring technical details or sharing project experience, we can make progress together.