版权声明:本文为博主原创文章,转载请注明出处 https://blog.csdn.net/qq_34160679/article/details/88180113
Vue 小应用
-
数组对象的删除操作
实例: list = [{ id: 1001, name: "zhangsan" }, { id: 1002, name: "lisi" }, { id: 1003, name: "wangwu" }] 背景: 根据ID 删除对象数组中对应的对象 1) function del(it) { this.list.some((item, i)=>{ if(item.id == id) { //通过索引删除数组 this.list.splice(i,1) // 在数组的SOME 方法中,如果 return true 就会终止这个循环 return true; } }) } 2) function del(it) { var index = this.list.findIndex(item =>{ if(item.id == id) { // 在数组的SOME 方法中,如果 return true 就会终止这个循环 return true; } }) //通过索引删除数组 this.list.splice(index,1) }
-
对象数组的模糊查询操作
实例: list = [{ id: 1001, name: "zhangsan" }, { id: 1002, name: "lisi" }, { id: 1003, name: "wangwu" }] 背景: 根据输入的keywords 模糊匹配name,并返回新的对象数组 1) 使用forEach() function search(keywords) { var newLit = [] this.list.forEach(item => { if(item.name.indexOf(keywords) != -1) { newList.push(item) } }) return newList } 2) 使用filter function search(keywords) { return this.list.filter(item => { // 注意: ES6中,为字符串提供了一个新方法,叫做 String.prototype.includes('要包含的字符串') //如果包含那么返回true if(item.name.includes(keywords)) { return item; } }) }
过滤器
-
Vue.filter(‘sexFormat’, function(sex) { } 定义一个过滤器
-
定义私有的过滤器,这种过滤器是只属于本 Vue 实例的
-
过滤器调用规则是就近原则,如果私有和全局过滤器名称相同,以私有为主。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Page Title</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="https://unpkg.com/vue/dist/vue.js"></script> </head> <body> <div id="app"> <!-- 1. 过滤器方法可以后面加参数sexFormat(arg, ...) 那么对应的在js 定义过滤器函数的时候,函数名加入参数。然后可以使用这些参数 --> {{sex | sexFormat}} <!-- 使用性别显示过滤器--> </div> </body> <script> // 定义一个 Vue 的过滤器,该过滤器用来处理性别显示, sexFormat 为过滤器的名称 // 这种定义方法定义出来的过滤器是全局的过滤器。 Vue.filter('sexFormat', function(sex) { if (sex == 1) { return '男' } else { return '女' } }) var vm = new Vue({ el: "#app", data: { sex: 2, }, filters: { // 定义私有的过滤器,这种过滤器是只属于本 Vue 实例的 // 过滤器调用规则是就近原则,如果私有和全局过滤器名称相同,以私有为主。 } }) </script> </html>