How to get custom attributes in vue

WBOY
Release: 2023-05-25 09:32:36
Original
2133 people have browsed it

In Vue, we can bind custom attributes to elements through the v-bind directive, and then obtain these custom attributes through JavaScript. Let's learn step by step how to get custom attributes.

  1. Bind custom attributes to elements

The v-bind directive allows us to dynamically bind attributes to elements in the form: v-bind: attribute name ="expression", or abbreviated as: attribute name="expression".

We can bind a custom attribute data-id to the element like this:

Copy after login

Among them, userId is a variable defined in the data of the component.

  1. Get custom attributes

We can get this custom attribute through JavaScript. In Vue, we can get the custom attributes of the element during the mounted() life cycle. The mounted() life cycle is a hook function triggered after the Vue instance is mounted on the DOM. At this time, the DOM can be manipulated.

Suppose we have bound the data-id attribute to the p element in the previous component, then we can get the attribute like this:

 
Copy after login

In the above example, we bind the p element The custom attribute data-id is bound, and a reference named "User" is given to the p element through the ref attribute. In the mounted() function, we obtain the p element through this.$refs.user, and call the getAttribute('data-id') method on it to obtain the custom attribute. Finally, we print out the obtained value, and the result is 123456.

  1. Using custom attributes

After obtaining the custom attributes, we can perform some corresponding operations. For example, when we click on the p element, the value of the element's custom attribute pops up:

 
Copy after login

The above is how to get the custom attribute in Vue. Bind custom properties through the v-bind directive, and then obtain these custom properties through JavaScript. Finally, you can use these properties in the need to extend the functionality of Vue.

The above is the detailed content of How to get custom attributes in vue. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!