1.全局注册
注册:main.js
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
Vue.directive('focus', {
inserted: function (el) {
el.focus()
}
})
new Vue({
render: h => h(App),
}).$mount('#app')
使用:App.vue
<template>
<div>
<input type="text" v-focus>
</div>
</template>
<script>
export default {
}
</script>
<style></style>
2.局部注册
注册与使用:
<template>
<div>
<input type="text" v-focus>
</div>
</template>
<script>
export default {
directives: {
focus: {
inserted: function (el) {
el.focus()
}
}
}
}
</script>
<style></style>
3.其他一些方法
<template>
<div>
<input type="text" v-focus="true">
</div>
</template>
<script>
export default {
directives: {
focus: {
//插入到html后,触发的事件
inserted: function (el, binding) {
// binding.value:获取设置的值
console.log(el, binding.value);
},
//数据加载后,触发的事件
update: function (el, binding) {
console.log(el, binding);
}
}
}
}
</script>
<style></style>