具体代码如下所示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<div>
<label>Id:
<input type="text" v-model='id'>
</label>
<label for="">Name:
<input type="text" v-model='name' @keyup.enter='add'>
</label>
<input type="button" value="添加" @click='addBtnFlag && add()'>
搜索:
<input type="text" v-model='keywords' id="search" v-focus v-color>
</div>
<!-- 注意: v-for 循环的时候 , key 属性只能使用 number获取string -->
<!-- 注意:key 在使用的时候,必须使 v-bind 属性绑定的形式 指定 key 的值 -->
<!--在组件中,使用v-for循环的时候,或者在一些特殊的情况中,如果 v-for 有问题 ,必须 在使用 v-for 的同时 ,指定 唯一的字符串/数字 类型 :key 值 -->
<!-- v-for 中的数据,都是直接从 data 上的 list 中直接渲染过来的 -->
<!-- 自定义一个 search 方法,同时 ,把所有的关键词,通过传参的形式,传递给了 search 方法 -->
<!-- 在 search 方法内部,通过 执行 for 循环,把所有符合 搜索关键字的数据,保存到 一个新数组中 返回 -->
<p v-for='item in search(keywords)' :key="item.id">
<input type="checkbox">
{{item.id}}---- {{item.name}}
<!-- <a @click='shift(index)'>删除</a> -->
-----------------<a @click.prevent="del(item.id)">删除</a>
</p>
</div>
<script>
//使用 Vue.directive() 定义全局的指令 v-focus
//其中:参数1:指令的名称,注意,在定义的时候,指令的名称前面,不需要加 v- 前缀,
//但是:再调用的时候,必须 在指令名称前面 加上 v- 前缀来进行调用
//参数2:是一个对象,这个对象身上,有一些指令相关的函数可以在特定的阶段,执行相关的操作
Vue.directive('focus', {
bind: function (el) {
//每当指令绑定到元素上的时候,会立即执行这个 bind 函数,只执行一次
//注意:在每个 函数中,第一个参数,永远是 el , 表示 被绑定了指令的那个元素,这个 el 参数,是一个原生的的JS对象
//在元素 刚绑定了指令的时候,还没有 插入到 DOM 中去,这时候,调用focus 方法没有作用
//因为,一个元素,只有插入DOM之后,才能获取焦点










