Home> Web Front-end> Vue.js> body text

What does this point to in vue?

下次还敢
Release: 2024-05-02 21:46:17
Original
353 people have browsed it

In Vue, the point of this depends on the context: the method points to the current Vue instance. The template points to the component context, including data, properties, calculated properties and methods. By default, the event handler points to the DOM element, which can be bound to the Vue instance through the bind or v-on modifier. The global object points to the Vue root instance and can access global configuration and methods.

What does this point to in vue?

What does this point to in Vue

In Vue, thethiskeyword points to different Object, depending on the context in which it is used.

1. Methods and computed properties

In methods and computed properties,thispoints to the current Vue instance. This means you can access the instance's data and methods, for example:

methods: { logThis() { console.log(this); }, },
Copy after login

When calling thelogThismethod,thiswill point to the current Vue instance.

2. Template

In the template,thispoints to the context object of the current component, which includes the following properties:

  • $data: The data object of the component
  • $props: The properties received by the component
  • $computed: Computed properties of the component
  • $methods: Methods of the component

For example, in the following template:

Copy after login

this .$data.messagewill access themessageproperty in the componentdataobject.

3. Event handler

In the event handler,thispoints to the DOM element that triggered the event. However,thiscan be bound to the current Vue instance by using thebindorv-onmodifiers.

For example:

methods: { handleClick(event) { console.log(this); // 指向 Vue 实例 }, },
Copy after login
Copy after login

4. Global object

Outside the Vue root instance,thiswill point to the global Vue object . This means you have access to global configuration and methods like:

console.log(this.$options.components); // 打印注册的全局组件 this.$mount(app); // 挂载 Vue 根实例
Copy after login

The above is the detailed content of What does this point to in vue?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
vue
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn