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
In Vue, thethis
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:
methods: { logThis() { console.log(this); }, },
When calling thelogThis
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 componentFor example, in the following template:
{{ this.$data.message }}
this .$data.message
will access themessage
property in the componentdata
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 thebind
orv-on
modifiers.
For example:
methods: { handleClick(event) { console.log(this); // 指向 Vue 实例 }, },
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:
console.log(this.$options.components); // 打印注册的全局组件 this.$mount(app); // 挂载 Vue 根实例
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!