这是我参与「第四届青训营 」笔记创作活动的第9天.
函数方法
find()
检测数组中满足指定条件的第一个元素:当数组中的元素在测试条件时返回 true 时, find() 返回符合条件的元素,之后的值不会再调用执行函数;如果没有符合条件的元素返回 undefined。
注意:不会对空数组进行检测。
isArray()
判断一个对象是否为数组,对象是数组返回 true,否则返回 false。
includes()
判断数组是否包含一个指定的值,如果是返回 true,否则false。
indexOf()
查找数组中指定元素第一次出现的索引位置:如果找到一个指定元素 item,则返回 item 的第一次出现的位置;如果没找到指定元素则返回 -1。开始位置的索引为 0。
push()
添加新元素到数组末尾,会改变原数组。
注意: 此方法改变数组的长度。
pop()
删除数组的最后一个元素并返回删除的元素,会改变原数组。
注意: 此方法改变数组的长度。
splice()
添加或删除数组中的元素,会改变原数组。
一个小样例:
html:
<div class="CollectList" v-if="!createcollect_flag">
<!-- 上方标题 -->
<div class="title">
<h1>选择收藏集</h1>
<div class="sub_title">选择或创建你想添加的收藏集</div>
<div class="closecollect" @click="closecollect">×</div>
</div>
<!-- 中间列表 -->
<div class="collectlist_container">
<ul class="collectlist">
<li v-for="(i, index) of collcectlist_this" :key="index" class="list_li">
<div class="list_li_left">
<span class="TextName">{{ i.name }}</span>
<span class="sub_title">{{ i.text_num }}篇文章·{{ i.collect_num }}订阅 </span>
</div>
<input type="checkbox" :value="index" @click="select_collect">
</li>
</ul>
</div>
<!-- 底部 -->
<div class="bottom">
<div class="bottom_left" @click="open_createcollect">
+ 新建收藏夹
</div>
<div class="bottom_right" @click="commit_collect">
确定
</div>
</div>
</div>
js:
name: "CollectList",
// props: ['collcectlist'],
props: {
collcectlist: {
type: Array,
required: true,//必要性
}
},
data() {
return {
select_collect_list: [],/*选中的收藏夹*/
collcectlist_this: this.collcectlist,
createcollect_flag: false,
}
},
methods: {
//打开创建收藏夹页面
open_createcollect() {
this.createcollect_flag = !this.createcollect_flag;
},
// 选中该收藏夹
select_collect(e) {
//当选定列表没有该标签时
if (this.select_collect_list.indexOf(e.target.value) == -1) {
// 增加该标签
console.log(e.target.value);
this.select_collect_list.push(e.target.value);
} else {
// 删除该标签
this.select_collect_list.splice(this.select_collect_list.indexOf(e.target.value), 1);
}
},
//关闭该页面
closecollect() {
this.$emit('closecollect', false);
console.log('关闭事件触发');
},
//提交选中集合并关闭页面
commit_collect() {
var commitlist = [];
for (let index = 0; index < this.select_collect_list.length; index++) {
commitlist.push(this.collcectlist_this[this.select_collect_list[index]]);
}
this.$emit('commit_collect', commitlist);
this.closecollect();
},
其中的
select_collect(e) {
//当选定列表没有该标签时
if (this.select_collect_list.indexOf(e.target.value) == -1) {
// 增加该标签
console.log(e.target.value);
this.select_collect_list.push(e.target.value);
} else {
// 删除该标签
this.select_collect_list.splice(this.select_collect_list.indexOf(e.target.value), 1);
}
},
indexOf和find对比,前者返回的是下标,后者返回的是元素本身,而前者格式为indexOf.(element),后者为find.(element)中的element为函数,返还值为过滤条件.