Table of contents
1. Private custom instructions
1. Private custom instructions
Private custom instruction: refers to the custom instruction defined inside the component, which can only be used in this component and cannot be used by other components
grammar:
Custom directives are defined under the directives node. Where el points to the bound native DOM object
The binding parameter is used to receive the value passed by the user
Look at the code below:
A custom directive is defined: v-color
<template>
<p v-color="color">Hello vue</p>
</template>
<script>
export default {
data() {
return {
color: "red"
}
},
directives: {
color: {
// el points to the bound native DOM object
// The binding parameter is used to receive the value passed by the user
bind(el, binding) {
el.style.color = binding.value
}
}
}
}
</script>
Note: The bind() function will only be executed when it is bound for the first time ! At this time, you need to use the update() function to monitor when the DOM element changes.
update() function, which will be triggered when the attribute value of the DOM element changes
directives: {
color: {
bind(el, binding) {
el.style.color = binding.value
},
upadte(el, binding) {
el.style.color = binding.value
}
}
}
The bind() and update() functions can be shorthand:
Premise: If the logic in the bind and update functions is exactly the same , the custom instruction in the object format can be shortened into a function format
directives: {
color(el, binding) {
el.style.color = binding.value
}
}
2. Global Custom Instructions
Globally shared custom directives need to be declared through ' Vue.directive() ' and written in the main.js file. The sample code is as follows:
// Global custom directive, color is the name of the custom directive
/* Vue.directive('color', {
bind(el, binding) {
el.style.color = binding.value
},
update(el, binding) {
el.style.color = binding.value
},
}) */
The following is shorthand, provided that the logic in the bind and update functions are exactly the same:
Vue.directive('color', function(el, binding) {
el.style.color = binding.value
})