Home > Web Front-end > Front-end Q&A > How to add attributes to vue (two methods)

How to add attributes to vue (two methods)

PHPz
Release: 2023-04-09 08:30:02
Original
3509 people have browsed it

There are two ways to add attributes in Vue:

Method 1: By defining attributes directly in data

We can define corresponding attributes in Vue's data, in Vue used in examples.

For example, if we now want to add a property to the Vue instance, we can write it like this:

<div id="app">
  <p>{{message}}</p>
  <button @click="setAttr">添加属性</button>
</div>
Copy after login
<script>
  let app = new Vue({
    el: '#app',
    data: {
      message: 'Hello World!',
      attr: '我是新添加的属性'
    },
    methods: {
      setAttr() {
        this.$set(this, 'attr', '我是新添加的属性');
      }
    }
  });
</script>
Copy after login

In the above code, we have defined a Vue instance app, and there are two attributes message in the data. And attr, the initial value of message is "Hello World!", and the initial value of attr is "I am a newly added attribute". In the method setAttr, we use $set to add the value of the attr attribute, and replace the attr attribute in data with "I am a newly added attribute".

Method 2: Define global and local instructions through Vue.directive

Vue.directive is a global method in Vue used to customize instructions. It can define a global instruction in a Vue instance. Implement operations on the DOM.

Suppose we now need to add a disabled attribute to a button, we can write like this:

<div id="app">
  <button v-custome-attr>按钮</button>
</div>
Copy after login
<script>
  Vue.directive('custome-attr', function(el, binding) {
    el.setAttribute('disabled', true);
  });

  let app = new Vue({
    el: '#app'
  });
</script>
Copy after login

In the above code, we use the Vue.directive method to define a global directive custome-attr , and add this directive to the button.

In the command function, we use the setAttribute method to add the disabled attribute to the button element to achieve the effect of disabling the button.

Summary:

Through the above two methods, we can easily add properties in Vue. Method 1: When adding attributes to an instance, you can directly use $set to add or modify attributes in data. Method 2 uses the Vue.directive method to define global instructions and add corresponding instructions to elements to operate the DOM.

The above is the detailed content of How to add attributes to vue (two methods). 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template