{{message}}
``````java"/>{{message}}
``````java">Home >Web Front-end >Front-end Q&A >How to add attributes to vue (two methods)
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>
<script> let app = new Vue({ el: '#app', data: { message: 'Hello World!', attr: '我是新添加的属性' }, methods: { setAttr() { this.$set(this, 'attr', '我是新添加的属性'); } } }); </script>
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>
<script> Vue.directive('custome-attr', function(el, binding) { el.setAttribute('disabled', true); }); let app = new Vue({ el: '#app' }); </script>
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!