Home  >  Article  >  Web Front-end  >  What does this point to in vue?

What does this point to in vue?

下次还敢
下次还敢Original
2024-05-02 21:46:17435browse

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, the this keyword points to different Object, depending on the context in which it is used.

1. Methods and computed properties

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

<code class="javascript">methods: {
  logThis() {
    console.log(this);
  },
},</code>

When calling the logThis method, this will point to the current Vue instance.

2. Template

In the template, this points 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:

<code class="html"><template>
  <p>{{ this.$data.message }}</p>
</template></code>

this .$data.message will access the message property in the component data object.

3. Event handler

In the event handler, this points to the DOM element that triggered the event. However, this can be bound to the current Vue instance by using the bind or v-on modifiers.

For example:

<code class="javascript">methods: {
  handleClick(event) {
    console.log(this); // 指向 Vue 实例
  },
},</code>
<code class="html"><button @click="handleClick">Click Me</button></code>

4. Global object

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

<code class="javascript">console.log(this.$options.components); // 打印注册的全局组件
this.$mount(app); // 挂载 Vue 根实例</code>

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!

Statement:
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