這個問題在這里已經有了答案: 如何在javascript中按屬性查找陣列中的物件? (2 個回答) 昨天關門。
我目前使用的編程語言是Vue. 我在這里有一些演示代碼:
<template>
<button @click="checkInList">Check</button>
</template>
<script>
import { ref } from "@vue/reactivity";
export default {
name: "App",
setup() {
const firstInput = ref("");
const secondInput = ref("");
const list = ref([
{ name: "lava", kind: "liquid" },
{ name: "air", kind: "gas" },
{ name: "water", kind: "liquid" },
{ name: "earth", kind: "object" },
]);
const checkInList = () => {
if (list.value.includes({ name: "lava", kind: "liquid" })) {
console.log("array includes lava");
// here I want to return the kind of that element, which will be liquid
}
};
return {
firstInput,
secondInput,
checkInList,
};
},
};
</script>
那么如何檢查是否list包含具有名稱的物件lava,然后回傳該物件的型別,它將是liquid?
uj5u.com熱心網友回復:
您可以使用所需的查找和回傳欄位:
const { ref } = Vue
const app = Vue.createApp({
setup() {
const firstInput = ref("");
const secondInput = ref("");
const list = ref([
{ name: "lava", kind: "liquid" },
{ name: "air", kind: "gas" },
{ name: "water", kind: "liquid" },
{ name: "earth", kind: "object" },
]);
const checkInList = () => {
return list.value.find(l => l.name.includes(firstInput.value)).kind
};
return {
firstInput,
secondInput,
checkInList,
};
},
})
app.mount('#demo')
So how can I check if list contains the object with name lava and then return the kind of that object, which will be liquid?
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
<button @click="checkInList">Check</button>
<input v-model="firstInput" />
<p>{{ checkInList() }}</p>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/455347.html
上一篇:Javascriptconst物件語法-這是在做什么?(在Vue腳本中使用)
下一篇:使用vue在螢屏上更新變數
