Skip to content

Instantly share code, notes, and snippets.

@myesn
Created August 7, 2022 15:17
Show Gist options
  • Save myesn/5faff4fba94c3478d96985cf94361d42 to your computer and use it in GitHub Desktop.
Save myesn/5faff4fba94c3478d96985cf94361d42 to your computer and use it in GitHub Desktop.
<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)"
/>&nbsp;
<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