# Vue中indexOf怎么用
在Vue.js開發中,`indexOf`是JavaScript原生數組和字符串方法,用于查找元素位置。本文將詳細介紹其在Vue中的使用場景、注意事項和實際案例。
## 一、indexOf方法基礎
### 1. 數組中的indexOf
```javascript
const arr = ['a', 'b', 'c'];
console.log(arr.indexOf('b')); // 輸出: 1
console.log(arr.indexOf('d')); // 輸出: -1(未找到)
const str = 'hello';
console.log(str.indexOf('e')); // 輸出: 1
console.log(str.indexOf('x')); // 輸出: -1
<template>
<div v-for="(item, index) in items" :key="index">
<span v-if="selectedItems.indexOf(item) !== -1">?</span>
{{ item }}
</div>
</template>
<script>
export default {
data() {
return {
items: ['蘋果', '香蕉', '橙子'],
selectedItems: ['香蕉']
}
}
}
</script>
computed: {
filteredList() {
return this.list.filter(item =>
item.name.toLowerCase().indexOf(this.searchTerm.toLowerCase()) !== -1
);
}
}
當在Vue的響應式數組中使用時,需注意:
// 正確做法
this.items.indexOf(value)
// 錯誤做法(破壞響應性)
const temp = this.items;
temp.indexOf(value)
<input v-model="searchText">
<script>
watch: {
searchText(newVal) {
if (this.fullText.indexOf(newVal) !== -1) {
this.showHighlight = true;
}
}
}
</script>
// 使用findIndex替代
const index = this.users.findIndex(user => user.id === targetId);
對于大型數組:
// 使用Set提高查找效率
const itemSet = new Set(this.largeArray);
itemSet.has(targetValue);
方法 | 返回值 | 適用場景 |
---|---|---|
indexOf | 索引/-1 | 簡單值查找 |
includes | true/false | 只需判斷是否存在 |
findIndex | 索引/-1 | 對象數組條件查找 |
// 聲明擴展類型
declare global {
interface Array<T> {
indexOf(searchElement: T, fromIndex?: number): number;
}
}
methods: {
isInCart(product) {
return this.cartItems.indexOf(product.id) !== -1;
},
addToCart() {
if (this.isInCart(this.currentProduct)) {
alert('已在購物車中');
}
}
}
區分大小寫:字符串查找區分大小寫
'Hello'.indexOf('h') // 返回-1
NaN處理:無法查找NaN
[NaN].indexOf(NaN) // 返回-1
引用類型比較:對象比較的是引用地址
const obj = {};
[{}].indexOf(obj) // -1
建議在Vue 3的Composition API中結合ref
和computed
使用,可以創建更高效的查找邏輯。
提示:對于復雜查找需求,推薦使用Lodash的_.findIndex等工具函數 “`
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。