1. Instruction life cycle and parameter transfer
<! DOCTYPEhtml>
<html >
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<title>Custom instruction</title>
</head>
<body>
<div id="app">
{{ message }}
<input v-if="isShow" v-focus:foo.a.b="focusVal" v-model="message">
<! --<input v-if="isShow" v-focus="focusObjVal" v-model="message">-->
<button type="button" @click="changeClick">Change the content</button>
<button type="button" @click="deleteClick">Remove components</button>
</div>
<script type="text/javascript">
var app = new Vue({
el: '#app'.data: {
message: 'Hello Vue! '.focusVal: '1111'.// Can be a method or an object
focusObjVal: { name : "Zhang".age : 18},
isShow: true
},
methods: {changeClick(){
this.message = "Clicked"
},
deleteClick(){
this.isShow = false}},directives: {
focus: {
// Only called once, when the directive is first bound to the element
bind(el,binding,vnode,oldVnode){
console.log("name",binding.name)
console.log("arg",binding.arg)
console.log("expression",binding.expression) / / expression
console.log("value",binding.value) // Corresponding to parsed content
console.log("modifiers",binding.modifiers) // the modifier {a:true,b:true} is used for special logic purposes. See click for.stop.prevent
},
// this is called when the bound element is inserted into the parent node.
inserted: function (el,binding) {
console.log("inserted")
el.focus()
},
// Called when the template to which the element is bound is updated, regardless of whether the binding value changes. By comparing the binding values before and after the update.
update(el,binding){
console.log("update")
console.log("modifiers",binding.modifiers)
},
// Called when the template to which the bound element belongs has completed an update cycle.
componentUpdated(el,binding){
console.log("componentUpdated")},// Only called once, when the instruction is unbound from the element.
unbind(el,binding){
console.log("unbind"(}}}});</script>
</body>
</html>
Copy the code
2. Interaction between instructions and external data
<template>
<div>
<div v-drag="{set:setVal,data: outData}">Custom instruction</div>
</div>
</template>
<script>
export default {
data(){
outData: 1.a: 2.b: 3
},
methods: {
setVal(val1,val2) {
this.a = val1;
this.b = val2; }},directives: {
drag: function(el,binding) {
var value1 = 11;
var value2 = 22;
binding.value.set(value1, value2); // External data receives internal value1 and value2, using setVal();
console.log(binding.value.data) // We get outData: 1}}}</script>
Copy the code