var vm = new Vue({
el: '#app',
data: {
id: '',
name: '',
keywords: '',
list: [
{ id: 1, name: '奔驰', ctime: new Date() },
{ id: 2, name: '宝马', ctime: new Date() },
],
},
methods: {
add() {
// 添加的方法
// 分析
// 1. 获取到 id 和 name,直接从 data 上面获取
// 2. 组织出一个对象
// 3. 把这个对象,调用数组的相关方法,添加到当前data上的list中
// 4. 在Vue中,已经实现了数据的双向绑定,每当我们修改了data中的数据,Vue会默认监听到数据的改动,自动把最新的数据,应用到页面上
// 5. 更多的是在进行 VM 中 Model 数据的操作,同时在操作 Mode 数据的时候,指定的业务逻辑操作
if (this.id == '' || this.name == '') return
this.list.push({ id: this.id, name: this.name, ctime: new Date() })
this.id = this.name = ''
},
del(id) {
// 根据id删除数据
// 分析
// 1. 如何根据 id 找到要删除对象的索引
// 2. 如果找到索引了,直接调用 数组的 splice 方法
// this.list.some((item, i) =>{
// if (item.id == id){
// this.list.splice(i, 1)
// // 在数组的 some 方法中,如果 return true,就会立即终止这个数组的后续循环
// return true;
// }
// })
var index = this.list.findIndex((item) => {
if (item.id == id) {
return true
}
})
this.list.splice(index, 1)
},
search(keywords) {
// 根据关键字进行搜索
// var newList = []
// this.list.forEach(item => {
// if (item.name.indexOf(keywords) != -1) {
// newList.push(item);
// }
// })
// return newList
// 注意:forEach some filter findIndex 这些都属于数组的新方法,都会对数组中的每一项,进行遍历执行相关的操作
return this.list.filter(item => {
// if(item.name.indexOf(keywords) != -1)
// 注意:ES6中,为字符串提供了一个新方法叫做,String.prototype.includes('要包含的字符串')
// 如果包含,则返回 true,否则返回 false
if(item.name.includes(keywords)){
return item
}
})
},
},
directives: {
'fontweight': {
bind: function(el, binding){
el.style.fontWeight = binding.value
},
'fontsize': function(el, binding){ // 注意,这个function 等于把代码写到了 bind 和 update 中去
el.style.fontSize = parseInt(binding.value) +'px'
}
}
}
})
- 在Vue实例中使用
directives
属性,定义私有指令 - 简写函数,等于把代码写到了
bind
和update
中去