除了使用默认的 vue 核心指令, 如 v-model, v-bind 等, 我们还可以自定义指令, 封装常用的功能.
如: 实现 input 框自动获得焦点, 且与之双向绑定的数据显示颜色为红色
自定义指令. gif
具体代码 https://gitee.com/zhiqiexing/vue.js/blob/b4b0198026b7a1aefdf52ee989382026b82a09d1/code/01/17.html
代码解析:
全局自定义指令
- // 自定义全局指令
- Vue.directive('focus', {
- inserted: function (el) {
- el.focus();
- }
- });
html 中调用自定义指令 focus
<input type="text" class="form-control" v-model="msg" v-focus>
自定义私有指令
- let vm = new Vue({
- el: "#app",
- data: {
- msg: '',
- },
- directives: { // 自定义私有指令
- color: function (el, binding) {
- el.style.color = binding.value
- }
- }
- })
调用私有指令 color
<h3 v-color="'red'">{{ msg }}</h3>
自定义指令
如想了解更多的 vue 实例, 请查阅我的 vue 笔记目录
来源: http://www.jianshu.com/p/666cf47d45f8