案例1:定义一个v-big指令,和v-text功能类似,但会把绑定的数值放大10倍
<!DOCTYPE html> <head> <meta charset="UTF-8"/> <script type="text/javascript" src="../js/vue.js"></script> </head> <body> <div id="root"> <h2>当前的n值是:<span v-text="n"></span></h2> <h2>放大10倍后的n值是:<span v-big="n"></span></h2> <button @click="n++">点我n+1</button> </div> </body> <script type="text/javascript"> Vue.config.productionTip = false; new Vue({ el:"#root", data:{ n:1 }, directives:{ //big 函数何时会被调用? //1、指令与元素成功绑定时; //2、指令所在的模板被重新解析时。 big(element,binding){ element.innerText = binding.value*10 } } }) </script>
案例2:定义一个v-fbind指令,和v-bind功能类似,但可以让其所绑定的input元素默认获取焦点
1、js操作页面元素基础:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .demo{ background-color: antiquewhite; } </style> </head> <body> <button id="btn">点我创建一个输入框</button> <script type="text/javascript"> const btn = document.getElementById('btn') btn.onclick=()=>{ const input = document.createElement('input') // input.focus() //写在页面渲染元素前,不生效 input.className = 'demo' //生效 input.value = 99 //生效 input.onclick = ()=>{ //生效 alert(1) } document.body.appendChild(input) input.focus() input.parentElement.style.backgroundColor = "skyblue"//input放入页面之后才生效 } </script> </body> </html>View Code
标签:Vue,自定义,指令,生效,input,btn,document From: https://www.cnblogs.com/technicist/p/17124990.html