vue之自定义指令(文本框获得焦点)
作者:互联网
app.vue
<template> <div> <h1>App 根组件</h1> <hr /> <!-- 使用组件 --> <my-home></my-home> </div> </template> <script> // 导入组件 import MyHome from './Home.vue' export default { name: 'MyApp', // 注册组件 components: { MyHome, }, } </script> <style lang="less" scoped></style>Home.vue
<template> <div class="home-container"> <h3 v-color="'red'">MyHome 组件 --- {{ count }}</h3> <hr /> <input type="text" class="form-control" v-focus v-color="'cyan'" /> <button type="button" class="btn btn-primary" @click="count += 1">+1</button> </div> </template> <script> export default { name: 'MyHome', data() { return { count: 0, } }, directives: { // focus: { // mounted(el) { // el.focus() // }, // }, }, } </script> <style lang="less" scoped> .home-container { border: 1px solid #efefef; box-shadow: 0px 1px 10px #efefef; border-radius: 4px; padding: 20px; margin: 20px; } input.form-control { width: 280px; } </style>
main.js(自定义全局指令)
// 声明全局自定义指令 // app.directive('focus', { // mounted(el) { // console.log('mounted') // el.focus() // }, // updated(el) { // console.log('updated') // el.focus() // }, // }) app.directive('focus', (el) => { el.focus() }) app.directive('color', (el, binding) => { el.style.color = binding.value })
标签:el,vue,自定义,app,focus,文本框,MyHome 来源: https://www.cnblogs.com/dxboot/p/16347851.html