Created
August 7, 2022 15:17
-
-
Save myesn/5faff4fba94c3478d96985cf94361d42 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script setup lang="ts"> | |
import { reactive, shallowRef, watchEffect } from "vue"; | |
interface Item { | |
id: number; | |
name: string; | |
} | |
const name = shallowRef<string>(""); | |
const itemLength = shallowRef<number>(0); | |
const items: Item[] = reactive([]); | |
function handleAppendClick() { | |
if (!name.value || items.some((item) => item.name === name.value)) { | |
return; | |
} | |
items.push({ | |
id: Date.now(), | |
name: name.value, | |
}); | |
name.value = ""; | |
} | |
function handleUpdateClick(id: number) { | |
const item = items.find((item) => item.id === id); | |
if (!item) { | |
return; | |
} | |
const newName = prompt("name:", item.name) as string; | |
if (!newName) { | |
return; | |
} | |
item.name = newName; | |
} | |
function handleRemoveClick(id: number) { | |
const index = items.findIndex((item) => item.id === id); | |
if (index > -1) { | |
items.splice(index, 1); | |
} | |
} | |
/** | |
* watch: items.length | |
* effect: itemLength change | |
*/ | |
watchEffect(() => { | |
itemLength.value = items.length; | |
}); | |
</script> | |
<template> | |
<div> | |
<input type="text" placeholder="typing your name" v-model="name" /> | |
<input type="button" value="append" @click="handleAppendClick" /> | |
</div> | |
<h3> | |
当前共有 <span>{{ itemLength }}</span> 个人 | |
</h3> | |
<ul v-if="items.length"> | |
<li v-for="{ id, name } in items" :key="id"> | |
{{ name }} | |
<input | |
type="button" | |
value="update" | |
@click="() => handleUpdateClick(id)" | |
/> | |
<input | |
type="button" | |
value="remove" | |
@click="() => handleRemoveClick(id)" | |
/> | |
</li> | |
</ul> | |
<span v-else>empty..</span> | |
</template> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment