既然是自己定义的指令也要符合vue 的规范,
第一, Vue中所有的指令,在调用的时候都以 v- 开头,
第二, 使用Vue. directive() 定义全局指令
第三 :其中参数1 是指令的名称 ,请不要在前面加v-
第四, 参数二 是一个对象,这个对象里封装一些方法,这些函数在特定的阶段,执行相关的操作,
下边就直接写个 文本框获取焦点指令如下
需要封装三个方法,
- bind, 绑定函数,只是执行一次
- insterted 插入到dom树里, 执行一次
- updated 更新的时候 ,有可能执行多次
注意 这三个函数 第一个参数永远是el,是原声js对象
全部的代码 参考 全部代码
<input type="text" v-model="key_words" class="form-control" v-focus>
Vue.directive('focus',{
bind:function(el){
el.focus()
},
inserted:function(el){
el.focus()
},
updated:function(el){
}
}
)
咱试试 是否可以呢 , 试了下没有生效,
总结:
bind 只是绑定属性,并没有在dom里, 所以要执行 inserted 就可以了,我们调用inserted
如下:
<input type="text" v-model="key_words" class="form-control" v-focus>
Vue.directive('focus',{
bind:function(el){
el.focus()
},
inserted:function(el){
el.focus()
},
updated:function(el){
}
}
)
经过测验已经可以了,我附上完整的代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link href="http://cdn.bootcss.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" >
<link href="https://cdn.bootcss.com/flat-ui/2.3.0/css/flat-ui.min.css" rel="stylesheet">
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">
</script>
</head>
<body>
<div id="pp" >
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">添加宠物</h3>
</div>
<div class="panel-body form-inline">
<label>id:</label>
<input type="text" v-model="id" class="form-control">
<label>name:</label>
<input type="text" v-model="name" class="form-control">
<input type="button" value="添加" @click="add" class="btn btn-primary">
<label>关键字搜索:</label>
<input type="text" v-model="key_words" class="form-control" v-focus>
</div>
</div>
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>id</th>
<th>Name</th>
<th>Ctime</th>
<th>Operation</th>
</tr>
</thead>
<tr v-for="item,index in search(key_words)" :key="item.id">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.ctime}}</td>
<td style="color: #0e9aef"><a href="" @click.prevent="del(item.id)">删除</a></td>
</tr>
</table>
</div>
<div>
<script>
Vue.directive('focus',{
bind:function(el){
el.focus()
},
inserted:function(el){
el.focus()
},
updated:function(el){
}
}
)
var vue=new Vue(
{
el: '#pp',
data: {
id:'',
name:'',
key_words: '',
list:[{id:1,name:"小狗",ctime:new Date()},{id:2,name:"小猫",ctime:new Date()},{id:3,name:"金鱼",ctime:new Date()},{id:4,name:"大闸蟹",ctime:new Date()}]
},
methods: {
add: function () {
this.list.push({id:this.id,ctime:new Date(),name: this.name})
this.name=this.id=''
},
del(id){
var index=this.list.findIndex((item)=>{ if(item.id == id){
return true;
}
}
)
this.list.splice(index,1)
},
search(key_words){
var newlist=[]
this.list.forEach(item => { // 调用了forEach 进行遍历
if( item.name.indexOf(key_words) !=- 1){ // 进行条件判断,看是否包含
newlist.push(item) //由于 forEach 没有返回数组 所以要进行push 到新的数组并返回、
}
});
return newlist
}
}
}
)
</script>
</div>
</body>
</html>