[Front-end development] JS synchronous and asynchronous calls, basic knowledge of Vue2

1. JS synchronous and asynchronous calls

Synchronous calls are when the code is executed in the order in which it was written, and each function must wait for the previous function to complete before it can be executed. This calling method blocks the execution of the code until the current function is completed before the next function can be executed.
Normal direct code is written down and called, which is a synchronous call.

Asynchronous calls are when code is not executed in the order in which it is written, but is executed after certain operations are completed. For example, when we use Ajax to request data, we can continue executing code after the request is sent without having to wait for the request to complete. Asynchronous calls do not block the execution of the code and can perform other operations in the background.

1. Asynchronous call function: use callback function to implement asynchronous call
function asyncFunction(callback) {
    
    
  console.log("Start");
  setTimeout(function() {
    
    
    console.log("End");
    callback();
  }, 2000);
}

console.log("Before function call");
asyncFunction(function() {
    
    
  console.log("Callback");
});
console.log("After function call");

In this example, we define an asyncFunction function that simulates an asynchronous operation using the setTimeout function and calls a callback function after the operation is completed. In the main program, we first output "Before function call", then call the asyncFunction function and pass in a callback function. Since asyncFunction is an asynchronous call, the code does not wait for the operation to complete, but directly executes the following code. Therefore, the order of output is "Before function call", "Start", "After function call", and then output "End" and "Callback" after 2 seconds.

2. Use Promise to implement asynchronous calls:
function asyncFunction() {
    
    
  console.log("Start");
  return new Promise(function(resolve, reject) {
    
    
    setTimeout(function() {
    
    
      console.log("End");
      resolve();
    }, 2000);
  });
}

console.log("Before function call");
asyncFunction().then(function() {
    
    
  console.log("Promise resolved");
});
console.log("After function call");

In this example, we define an asyncFunction function that returns a Promise object and calls the resolve function after the asynchronous operation is completed. In the main program, we first output "Before function call", then call the asyncFunction function, and use the then method to register a callback function. Since asyncFunction is an asynchronous call, the code does not wait for the operation to complete, but directly executes the following code. Therefore, the order of output is "Before function call", "Start", "After function call", and then output "End" and "Promise resolved" after 2 seconds.

3. Use async/await to implement asynchronous calls:
async function asyncFunction() {
    
    
  console.log("Start");
  await new Promise(function(resolve, reject) {
    
    
    setTimeout(function() {
    
    
      console.log("End");
      resolve();
    }, 2000);
  });
}

console.log("Before function call");
asyncFunction().then(function() {
    
    
  console.log("Promise resolved");
});
console.log("After function call");

In this example, we define an asyncFunction function that waits for the asynchronous operation to complete using the await keyword and continues execution after the operation completes. In the main program, we first output "Before function call", then call the asyncFunction function, and use the then method to register a callback function. Since asyncFunction is an asynchronous call, the code does not wait for the operation to complete, but directly executes the following code. Therefore, the order of output is "Before function call", "Start", "After function call", and then output "End" and "Promise resolved" after 2 seconds.

2. Basic knowledge of Vue2

Vue official documentation

You can use vue Temple to call data and methods functions, and use v-for to traverse lists to build web pages.
Can re-encapsulate the axios library and conduct unified management of APIs, and can use low-code platforms such as strapi to build simple cms.
Able to use nuxt.js to develop websites based on SSR rendering, and use commitlint specifications, husky hooks, etc. for front-end engineering management

Vue2 mainly consists of the following parts:

These are the main building blocks of Vue2: Directives & Instances, Components & Templates, Data Binding and Lifecycle Hooks . Together they form the basic structure of a Vue application and provide rich functionality and development methods.

  • Directives: Vue's directives are special HTML attributes used to add specific behaviors and functions to elements. Directives are represented by the v- prefix and are dynamically bound via data in the Vue instance. For example, v-bind, v-on, v-if, v-for, etc.

  • Instance: The core of a Vue application is a Vue instance. Use new Vue() to create a Vue instance, which is the root instance of the Vue application and is used to manage the application's data, methods, life cycle hooks, etc. Vue instances allow you to use features such as data binding, directives, and event handling in templates.

  • Components: Vue2 supports component-based development, allowing applications to be split into multiple reusable components. Components are extensions of Vue instances, with their own templates, data, methods and lifecycle hooks. Components can be nested, reused, and interact with each other through communication mechanisms.

  • Templates: Vue uses HTML-based template syntax to bind the data and methods of Vue instances to the DOM. Templates can contain interpolation expressions, instructions, event handling, etc., used to dynamically generate and update DOM elements.

  • Data Binding: Vue2 provides the capability of two-way data binding, which can dynamically bind data to the template. When the data changes, the template will automatically update, and vice versa. This enables responsive updating of data and simplifies the development process.

  • Lifecycle Hooks: Vue instances have a series of lifecycle hook functions that can insert code logic at different stages. For example, created, mounted, updated, destroyed, etc., you can perform corresponding operations in these hook functions.

1. Basic concepts & commonly used v instructions in dom

Install Vue.js: You can use Vue.js by introducing the Vue.js CDN link in your HTML file. Add the following code in the tag:

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>

Create a Vue instance: Create a Vue instance in a JavaScript file to manage your application.

var app = new Vue({
    
    
  el: '#app', // 绑定Vue实例到HTML元素
  data: {
    
    
    message: 'Hello Vue!' // 数据属性
  },
  methods: {
    
    
    changeMessage: function () {
    
    
      this.message = 'New message'; // 方法
    }
  }
});

Template syntax: Vue uses a simple template syntax that allows you to bind data into HTML. In an HTML file, you can use double curly brace interpolation expressions to display data from a Vue instance.
Event handling: You can use the v-on directive to listen for DOM events and call methods in the Vue instance when triggered.

<div id="app">
  <p>{
    
    {
    
     message }}</p>
  <button v-on:click="changeMessage">Change Message</button>
</div>

v-on (abbreviated as @): used to listen to DOM events and trigger corresponding methods. Can monitor any DOM event, such as click, input, keydown, etc. For example:

<button v-on:click="handleClick">Click me</button>

Conditional rendering: You can use the v-if directive to render or destroy HTML elements based on conditions .

<div id="app">
  <p v-if="isVisible">Visible</p>
  <p v-else>Hidden</p>
</div>

List rendering: You can use the v-for directive to render a list based on data from an array or object .

<div id="app">
  <ul>
    <li v-for="item in items">{
    
    {
    
     item }}</li>
  </ul>
</div>

v-show: Determine whether to display elements based on conditions (through the display attribute of CSS). For example:

<div v-show="isVisible">Visible</div>

v-bind (abbreviated as:): Binds HTML attributes or data of Vue instances. For example:
v-bind (abbreviated as:): used to dynamically bind attributes of HTML elements. Any HTML attributes can be bound, such as class, style, href, etc. For example:

<img v-bind:src="imageSrc">
<div v-bind:class="{ active: isActive, 'text-danger': hasError }"></div>

v-model: Creates a two-way binding between the form element and the data of the Vue instance. For example:

<input v-model="message">

v-text: Update the text content of the element. Similar to double curly brace interpolation expression ({ { }}), but only updates text content and does not parse HTML. For example:

<p v-text="message"></p>

v-html: Update the HTML content of the element. The data in the Vue instance will be parsed into HTML and updated into the element. Note that it should be used with caution to avoid XSS attacks. For example:

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

v-pre: Skip the compilation process of elements or components in the Vue instance and directly render their original content onto the page. Mainly used to display static content that does not require dynamic binding. For example:

<pre v-pre>{
    
    {
    
     rawText }}</pre>

2. Vue2 instance & data binding (#el first, then v-bind)

Instances of Vue2 are the core of Vue applications. You can use new Vue() to create a Vue instance, which allows you to manage your application's data, methods, lifecycle hooks, etc.

When creating a Vue instance, you need to pass in an options object, which contains the configuration items of the Vue instance. The following is an example of creating a basic Vue instance:

var app = new Vue({
    
    
  el: '#app', // 将Vue实例挂载到指定的HTML元素上
  data: {
    
    
    message: 'Hello Vue!' // 数据属性
  },
  methods: {
    
    
    changeMessage: function () {
    
    
      this.message = 'New message'; // 方法
    }
  },
  created: function () {
    
    
    console.log('Vue实例已创建');
  }
});

In the above example, a Vue instance is created and mounted on the HTML element with the id app. Configuration options for the instance include:

  • el: Specifies the selector or DOM element of the HTML element to be mounted by the Vue instance.
  • data: Defines the data attributes of the Vue instance, which can be data bound in the template.
  • methods: methods that define Vue instances, which can be called in templates or other methods.
  • created: Hook function, called immediately after the Vue instance is created, can perform some initialization operations.

By accessing a Vue instance, you can get and modify data properties, call methods, and listen to lifecycle hook functions as needed. For example, use a double curly brace interpolation expression in a template to get the value of a data attribute:

<div id="app">
  <p>{
    
    {
    
     message }}</p>
  <button v-on:click="changeMessage">Change Message</button>
</div>

In the above example, the value of the message attribute will be dynamically bound in the Vue instance and displayed in the template. Clicking the button will call the changeMessage method to modify the value of the message attribute.

Vue instances provide a rich set of features and options for building interactive web applications. You can define data, methods, computed properties, listeners, etc. in the instance, and you can also use directives, components, and routing to extend Vue's functionality.

————————————————————————————————————

Vue2 provides a flexible and powerful data binding mechanism that allows you to dynamically bind data to templates and achieve automatic data updating. Vue2 data binding mainly includes the following aspects:

1. Interpolation:
Vue2 uses double curly braces { { }} to create interpolation expressions to bind the data in the Vue instance to the template. For example:

<p>{
    
    {
    
     message }}</p>

In the above example, message is a data attribute in the Vue instance, and its value is dynamically inserted into <p>the tag.

2. Directives: Directives are special HTML attributes in Vue, starting with v-. Through directives, you can bind an element's properties, events, and content to data in a Vue instance. Commonly used instructions include v-bind and v-on. For example:

<img v-bind:src="imageUrl">
<button v-on:click="handleClick">Click me</button>

In the above example, the v-bind instruction binds the src attribute to the imageUrl data to implement a dynamic image path. The v-on directive listens to the click event of the button and calls the handleClick method.

3. Two-way Data Binding:
Vue2 provides the v-model instruction to implement two-way data binding of form elements. It can bind the value of the form element to the data attributes in the Vue instance. When the value of the form element changes, the data attributes will be automatically updated. For example:

<input v-model="message">

In the above example, message is a data attribute in the Vue instance. The value of the input box is two-way bound to the message. Changes in either side will update the other side synchronously.

4. Computed Properties:
Vue2 allows you to define computed properties, which can be calculated based on the values ​​of other data properties and return a new value. Computed properties can be data-bound in the template. When the dependent data changes, the calculated properties will be automatically recalculated. For example:

var app = new Vue({
    
    
  data: {
    
    
    firstName: 'John',
    lastName: 'Doe'
  },
  computed: {
    
    
    fullName: function () {
    
    
      return this.firstName + ' ' + this.lastName;
    }
  }
});

In the above example, fullName is a calculated property. The complete name is calculated based on the values ​​​​of firstName and lastName, and can be data bound in the template.

Through these data binding mechanisms, Vue2 implements responsive updating of data. When the data changes, the relevant templates will automatically update, thereby achieving synchronization of data and views. This greatly simplifies the development process and improves application maintainability and user experience.

——————————————————————
You need to use the el option to mount the Vue instance to the HTML element first, and then use v-bind in the corresponding child element. Perform data binding.

When a Vue instance is mounted to an HTML element, Vue will use the HTML element and its sub-elements as the management scope of the Vue application. This means that the Vue instance can access and control the data, methods, and instructions of the mounted element and its children.

Therefore, after mounting the Vue instance, you can use the v-bind directive on the child elements of the mounted element to bind the data in the Vue instance to the attributes of the child elements. In this way, the attribute values ​​of the child elements will be updated as the data in the Vue instance changes.

The following is an example that shows the process of first using el to mount a Vue instance, and then using v-bind for data binding in child elements:

<div id="app">
  <p v-bind:title="message">Hover over me</p>
</div>

var app = new Vue({
    
    
  el: '#app',
  data: {
    
    
    message: 'This is a tooltip'
  }
});

In the above example, the Vue instance is first mounted to the HTML element with the id app through the el option. Then, in the child elements of that element

Use the v-bind directive to bind the message data attribute to the title attribute. When the value of message changes, the title attribute of the child element will be updated accordingly.

Therefore, make sure to use el to mount the Vue instance first, and then use v-bind in the corresponding child element for data binding to ensure that the Vue instance can correctly manage and update the bound data.

3. Vue2 components & templates (template, script, export default)
  • Components: Components are the core concept in Vue2, which divide an application into multiple independent and reusable modules. Each component contains its own templates, data, methods, and styles that can be combined and nested to build complex applications. Components make code easier to maintain, test, and reuse, and provide better organization. In Vue2, you can define components using the Vue.component method or single-file components (.vue files).

  • Templates: Templates are HTML codes used to describe components in Vue2. The template defines the structure and layout of the component and uses the instructions and syntax provided by Vue to implement dynamic data binding and logic control. In templates, you can bind data and methods to HTML elements through interpolation, instructions, event binding, etc. Vue's template syntax is very intuitive and flexible, allowing you to easily create dynamic and responsive user interfaces.

  • Single File Components: Single File Components are a way of organizing and writing components in Vue2. It encapsulates the component's template, logic, and styles in a separate file, usually using .vue as the file extension. Single-file components provide better code organization and maintainability, allowing developers to define and manage components more clearly. Single-file components can use preprocessors (such as Babel, TypeScript, Sass, etc.) to enhance the development experience and functionality.

In Vue2, you can define and register components using global registration and local registration.

Global registration of components:
Global registration allows you to use the component anywhere in the application. It is suitable for components that are widely used throughout the application.

Vue.component('component-name', {
    
    
  // 组件的选项
});

Among them, component-name is the name of the component and can be customized. A component option is an object containing templates, data, methods, etc. that define the behavior and appearance of the component.

Use globally registered components in templates, example:

<div id="app">
  <component-name></component-name>
</div>

Local registration of components:
Local registration allows you to use the component inside a specific Vue instance or component. It is suitable for components that are only needed within a specific scope.

In the options of the Vue instance or component, use the components attribute to register the component locally. The syntax is as follows:

new Vue({
    
    
  components: {
    
    
    'component-name': {
    
    
      // 组件的选项
    }
  },
  // 其他选项
});

Among them, component-name is the name of the component and can be customized. A component option is an object containing templates, data, methods, etc. that define the behavior and appearance of the component.

Use locally registered components in templates, example:

<div id="app">
  <component-name></component-name>
</div>

Whether registered globally or locally, once a component is registered, it can be used in the corresponding template and rendered and interacted with according to the behavior and appearance defined by the component options.

The following is an example showing the usage of globally registered and locally registered components:

<div id="app">
  <global-component></global-component>
  <local-component></local-component>
</div>

// 全局注册组件
Vue.component('global-component', {
    
    
  template: '<div>This is a global component</div>'
});

// 局部注册组件
var LocalComponent = {
    
    
  template: '<div>This is a local component</div>'
};

new Vue({
    
    
  el: '#app',
  components: {
    
    
    'local-component': LocalComponent
  }
});

When it comes to code examples for Vue2 components and templates, here is a simple example:

<!-- index.html -->
<div id="app">
  <my-component></my-component>
</div>

// main.js
Vue.component('my-component', {
    
    
  template: `
    <div>
      <h2>{
     
     { message }}</h2>
      <button @click="updateMessage">Update Message</button>
    </div>
  `,
  data() {
    
    
    return {
    
    
      message: 'Hello, Vue!'
    };
  },
  methods: {
    
    
    updateMessage() {
    
    
      this.message = 'Updated message!';
    }
  }
});

new Vue({
    
    
  el: '#app'
});

In the above example, we defined a Vue instance in index.html and used <my-component>``</my-component>tags in that instance. This label represents our custom component my-component.

In main.js, we register the my-component component globally using the Vue.component method. The component options contain a template, which contains a <h2>label and a button. The template uses the interpolation expression { { message }} to display the data in the component, and uses the @click directive to bind the click event of the button.

The component's options also include a data method, which returns an object containing the message attribute. The initial value of the message attribute is 'Hello, Vue!'.

The component options also define a methods object, which contains an updateMessage method. This method is called when the button is clicked, updating the value of the message attribute.

When the application runs, <my-component>the tag is rendered as the component's template, displaying Hello, a Vue! title, and a button. When the button is clicked, the value of the message attribute will be updated to 'Updated message!', causing the data in the template and the view to be updated.

This example shows the basic usage of components and templates in Vue2, including component definition, template usage, data binding and method triggering. In this way, you can create reusable components and implement dynamic data rendering and interactive behavior in templates.

In Vue2, <template>tags are special tags used to wrap Vue component templates. It plays the role of a container in the definition of the Vue component, used to encapsulate the structure and layout of the component, and will not be rendered in the final rendered HTML.

The main purpose of using <template>tags is to provide a block-level container that can contain multiple elements without introducing additional parent elements. In a template, you can include any number of HTML elements, directives, interpolation expressions, and other Vue template syntax.

Here is an example that demonstrates how to use <template>tags to organize templates for Vue components:

<template>
  <div>
    <h2>{
    
    {
    
     title }}</h2>
    <p>{
    
    {
    
     message }}</p>
    <button @click="handleClick">Click me</button>
  </div>
</template>

<script>
export default {
    
    
  data() {
    
    
    return {
    
    
      title: 'Hello, Vue!',
      message: 'Welcome to my Vue component.'
    };
  },
  methods: {
    
    
    handleClick() {
    
    
      alert('Button clicked!');
    }
  }
};
</script>

<style scoped>
h2 {
    
    
  color: blue;
}

button {
    
    
  background-color: green;
  color: white;
}
</style>

In the example above, <template>the tag contains the component's entire template content, including a title, message, and a button. The template uses interpolation expressions { { title }} and { { message }} to dynamically display data, and uses the @click directive to bind the click event of the button.

Note that <template>the tag itself will not be rendered in the final rendered HTML, it is just used to organize and wrap the template content. This way we can define the structure of the component without introducing additional meaningless parent elements.

In addition, <template>tags also support <slot>the use of tags for inserting content passed by parent components. This allows more flexibility in defining the layout and structure of components.

Finally, it should be noted that <template>tags support scoped attributes, which can limit styles to the current component. This means that <style scoped>styles defined in tags will only be applied to the current component's template, and the same selector elsewhere will not be affected.

<script>The tags and export default {} are not the Vue instance itself, but are used to define options for the Vue component and how to export the component.

In the definition of Vue components, <script>tags are used to write the logical part of the component, including data, methods, life cycle hooks, etc. <script>The content inside the tag will be parsed and executed by Vue, thereby creating a Vue component instance.

The export default {} syntax is the way to export Vue components. In the definition of a Vue component, export the component's options object through the export default syntax so that it can be introduced and used elsewhere. In this way, we can introduce the component in other Vue files or entry files, and register and use the component in the Vue application.

Here is an example that demonstrates how to use

<template>
  <div>
    <h2>{
    
    {
    
     message }}</h2>
    <button @click="updateMessage">Update Message</button>
  </div>
</template>

<script>
export default {
    
    
  data() {
    
    
    return {
    
    
      message: 'Hello, Vue!'
    };
  },
  methods: {
    
    
    updateMessage() {
    
    
      this.message = 'Updated message!';
    }
  }
};
</script>

In the above example, <script>a Vue component's options object is defined inside the tag. The options object contains a data attribute, which returns an object containing a message attribute, and a methods object, which contains an updateMessage method.

Through the export default syntax, the component's options object is exported so that it can be introduced and used elsewhere. For example, you can use the import syntax to import the component in other files, and register and use it in the Vue application.

For example, assuming the above component is defined in a file named MyComponent.vue, we can introduce and register it in another file:

<!-- index.html -->
<div id="app">
  <my-component></my-component>
</div>

// main.js
import Vue from 'vue';
import MyComponent from './MyComponent.vue';

Vue.component('my-component', MyComponent);

new Vue({
    
    
  el: '#app'
});

In the above example, we use the import syntax to introduce the component exported in the MyComponent.vue file, and use the Vue.component method to register the component as a global component. This way we can use <my-component>the tag in our application and instantiate the component.

MyComponent has been registered as a global component in main.js and registered through the Vue.component method. Next, you can use a tag in your application's template <my-component>to call the component.

In this example, the MyComponent component's template might contain a title, buttons, and other content. When <my-component>the tag is rendered, the content in the template will be displayed on the page.

By using component tags in templates, you can call and instantiate the same component multiple times in a Vue application, thereby displaying the component's content and behavior in different locations.

To summarize, <script>tags and export default {} syntax are the way to define and export Vue components. <script>The content inside the tag will be parsed and executed by Vue, creating a Vue component instance. Through the export default syntax, we can introduce and register the component in other files to use it in the Vue application.

3. Life cycle hooks

In Vue2, a component's lifecycle hook is a set of methods that are called at different lifecycle stages of the component, allowing you to execute custom logic at specific points in time. The following are the most commonly used lifecycle hooks in Vue2:

beforeCreate: Called before the instance is created. At this time, the component instance has not been initialized, and the component's data and methods cannot be accessed.

created: Called after the instance is created. At this point, the instance of the component has been created and the data and methods of the component can be accessed, but it has not yet been mounted on the DOM.

beforeMount: Called before the component is mounted to the DOM. At this point, the component has been compiled, but the contents of the mount point have not yet been replaced.

mounted: Called after the component is mounted to the DOM. At this point, the component has been inserted into the page, and the DOM element of the component can be accessed, as well as the root DOM element of the component through this.$el.

beforeUpdate: Called before the component is updated. When the component's data changes, re-rendering is triggered, and the beforeUpdate hook is called before re-rendering.

updated: Called after the component is updated. The updated hook is called when the component's data changes and re-rendering is completed. At this point the DOM has been updated and you can perform operations interacting with the DOM.

beforeDestroy: Called before the component is destroyed. Before the component is destroyed, some cleanup work can be performed, such as clearing timers, canceling subscriptions, etc.

destroyed: Called after the component is destroyed. After the component is destroyed, some final cleanup work can be performed, and the instance of the component is no longer available.

In addition to the commonly used life cycle hooks mentioned above, Vue2 also provides some other life cycle hooks, such as activated, deactivated, errorCaptured, etc., for handling advanced uses and special situations of components.

By defining these lifecycle hook methods in the component, you can execute custom logic at different stages, such as initializing data before creating the component, triggering additional operations after the component is updated, etc. Lifecycle hooks provide you with the flexibility to control component behavior and allow you to interact with the component's lifecycle.

It should be noted that in Vue3, life cycle hooks have undergone some changes, and some hooks have been renamed or merged, so you need to pay attention to the differences when using them in Vue3.

4. Vue2 parent-child components pass values ​​(Props, $emit)

In Vue2, parent components can pass data to child components, and child components can also send data to parent components through events. The following are several common ways of passing values ​​between parent and child components:

1. Props (properties): Parent components can pass data to child components through props. In the child component, declare the properties passed by the parent component through the props option and use them in the template. Data changes in the parent component will automatically be reflected in the child component.

<!-- ParentComponent.vue -->
<template>
  <div>
    <child-component :message="parentMessage"></child-component>
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
    
    
  components: {
    
    
    ChildComponent
  },
  data() {
    
    
    return {
    
    
      parentMessage: 'Hello from parent'
    };
  }
};
</script>

<!-- ChildComponent.vue -->
<template>
  <div>
    <p>{
    
    {
    
     message }}</p>
  </div>
</template>

<script>
export default {
    
    
  props: ['message']
};
</script>

2. Custom events: Child components can trigger custom events through the $emit method and pass data to the parent component. In the parent component, you can capture the data sent by the child component by listening to a custom event on the child component's tag.

<!-- ParentComponent.vue -->
<template>
  <div>
    <child-component @custom-event="handleChildEvent"></child-component>
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
    
    
  components: {
    
    
    ChildComponent
  },
  methods: {
    
    
    handleChildEvent(data) {
    
    
      console.log('Received data from child:', data);
    }
  }
};
</script>

<!-- ChildComponent.vue -->
<template>
  <div>
    <button @click="sendDataToParent">Send Data to Parent</button>
  </div>
</template>

<script>
export default {
    
    
  methods: {
    
    
    sendDataToParent() {
    
    
      const data = 'Data from child';
      this.$emit('custom-event', data);
    }
  }
};
</script>

In this way, when the button in the child component is clicked, the sendDataToParent method is triggered, which triggers a custom event named custom-event through $emit and passes the data to the parent component. The handleChildEvent method in the parent component captures and processes the data sent by the child component.

These are commonly used parent-child component value transfer methods in Vue2. Through props and custom events, two-way data transmission and communication can be carried out between parent and child components.

5. Vue2 component reference (ref, $, this and other symbols)

In Vue2, use the ref attribute to add a reference to a Vue component or DOM element. Through the ref attribute, you can access child components or DOM elements in the parent component and obtain references to them through this.$refs.

When you use ref="xxx" in the template to add a reference to a component or DOM element, Vue will create an attribute in the $refs object of the parent component. The attribute name is the reference name you specified (xxx), and the attribute value is the corresponding Component instance or DOM element.

Then, you can directly access this component instance or DOM element through this.$refs.xxx to perform operations or call its methods.

For example, suppose you have a child component ChildComponent and add a reference to it using ref in the parent component's template:

<!-- ParentComponent.vue -->
<template>
  <div>
    <child-component ref="myChild"></child-component>
    <button @click="callChildMethod">Call Child Method</button>
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
    
    
  components: {
    
    
    ChildComponent
  },
  methods: {
    
    
    callChildMethod() {
    
    
      this.$refs.myChild.childMethod();
    }
  }
};
</script>

In the above example, the ChildComponent is referenced with ref="myChild" added. Then, in the callChildMethod method of the parent component, you this.$refs.myChildcan obtain the instance of ChildComponent and call its childMethod method.

It should be noted that it this.$refsis an object, the attribute name corresponds to the value of ref, and the attribute value corresponds to the component instance or DOM element. this.$refs.xxxTherefore, the corresponding component or DOM element can be accessed in the parent component and then further operations can be performed.

However, it should be noted that when using this.$refs, you need to pay attention to the timing of the life cycle and ensure that you access the component after it has been rendered to the DOM. Otherwise, you may get undefined or inaccurate results.

I hope this can help you understand the principle of referencing and calling components or DOM elements through ref and this.$refs in Vue2.

——————————————————————————————————————
In Vue2, $symbol is the prefix of a special property and method of Vue instance , used to access the built-in properties and methods of the Vue instance and the functions provided by the plug-in. It provides a convenient way to interact with Vue instances.
Here are some common properties and methods starting with $:

$data: Data object used to access Vue instances. Data can be obtained or modified through this.$data.

$props: Used to access the properties passed by the parent component to the current component. You can get the properties passed by the parent component through this.$props.

$emit: Used to trigger custom events inside components. A custom event can be triggered through this.$emit(event, data) and the corresponding data can be passed.

$on: Used to listen to custom events inside the component. You can listen to a custom event through this.$on(event, callback) and specify the corresponding callback function.

$watch: Used to monitor data changes in Vue instances. Through this.$watch(property, callback), you can monitor changes in the specified properties and execute the corresponding callback function.

$router: Used to access Vue Router instances, providing navigation-related methods and properties, such as this.$router.push() for page jumps.

$store: Used to access the Vuex store instance, providing state management methods and properties, such as this.$store.dispatch() is used to trigger an action.

In addition to the above built-in properties and methods, plug-in developers can also add custom properties and methods to the Vue instance through the $ symbol for use in components.

In short, $a symbol is a special prefix for a Vue instance, used to access the built-in properties, methods and functions provided by the Vue instance, and provides a convenient way to interact and operate with the Vue instance.

——————————————————————

In the Vue instance, use this.xxx to get the following values:

Data Properties: When you define a property in the data option of the Vue instance, you can obtain and modify the value of the property through this.xxx. For example, if the message attribute is defined in data, you can use this.message to get and modify its value.

Computed Properties: When you define a computed property in the computed option of the Vue instance, you can get the value of the computed property through this.xxx. For example, if you have a computed property fullName, you can use this.fullName to get its value.

Methods: When you define a method in the methods option of the Vue instance, you can call the method through this.xxx(). For example, if there is a method sayHello, you can use this.sayHello() to call it.

Watchers: When you define a listener in the watch option of the Vue instance, you can get the current value of the monitored property through this.xxx. For example, if you have a listener watch: { message: function(newVal) { // do something } }, you can use this.message to get the current value of the message property.

Lifecycle Hooks: When you use lifecycle hook functions in a Vue instance, such as created, mounted, etc., you can access the Vue instance itself through this.xxx. For example, in the created hook function, you can use this.$el to access the root DOM element of the Vue instance.

It should be noted that, except for the above situations, this.xxx cannot directly obtain other custom properties or methods. If you want to add custom properties or methods to a Vue instance, you can add them to the Vue instance through the methods option of the Vue instance or through the $ symbol.

In short, through this.xxx, you can get the current values ​​of data attributes, calculated attributes, methods, and listeners in the Vue instance, as well as access specific attributes and methods of the Vue instance itself.

Guess you like

Origin blog.csdn.net/qq_33957603/article/details/133212759