Vue 中提供了14个比较常用的指令,如v-text、v-html、v-on、v-model等,而在实际的开发过程中,对于表单元素获取焦点也会常用到,而autofucos属性在vue中是失效的(移动端的Safarit也会失效),那如何来实现这个效果,这个时候就需要用到自定义的指令了。
下面就简单两个例子v-focus(获取焦点)、v-color(设置字体颜色):
<body>
<div id="app">
<h2 v-color>{
{msg}}</h2>
<input type="text" v-focus />
</div>
<script src="vue.js"></script>
<script>
//注册一个全局自定义指令 `v-focus`
Vue.directive("focus", {
inserted(el) {
el.focus();
},
});
//注册一个全局自定义指令 `v-color`
Vue.directive("color", {
bind(el) {
el.style.color = "red";
},
});
const vm = new Vue({
el: "#app",
data: {
msg: "自定义指令",
},
});
</script>
</body>
效果如下: