Vue.js3 Composition API CRUD
執行結果
<div id="app">
<input type="text" v-model="text">
<button type="button" @click="addItem">增加文字</button>
<ul>
<li v-for="item in data" :key="item.id">
{{item.text}}
<button type="button" @click="editItem(item)">編輯</button>
<button type="button" @click="removeItem(item)">移除</button>
</li>
</ul>
<hr>
<input type="text" v-model="temp.text">
<button type="button" @click="doneEdit">編輯完成</button>
</div>
<script type="module">
import { createApp, ref, onMounted } from 'https://cdnjs.cloudflare.com/ajax/libs/vue/3.4.15/vue.esm-browser.prod.min.js';
const app = createApp({
setup() {
const text = ref('Tree');
const data = ref([]);
const temp = ref({});
const idPlus1 = ref(0);
// log
function getTest(){
console.log(text.value);
};
// 新增
function addItem() {
data.value.push({
id: idPlus1.value,
text: text.value
});
text.value = "";
idPlus1.value++;
};
// 刪除
function removeItem(inItem) {
const index = data.value.findIndex(o => o.id === inItem.id);
data.value.splice(index, 1);
};
// 編輯
function editItem(inItem) {
temp.value = { ...inItem };
};
// 資料寫回
function doneEdit() {
const index = data.value.findIndex(o => o.id === temp.value.id);
data.value[index] = temp.value;
temp.value = {};
};
// 初始化
onMounted(()=>{
getTest();
});
// 必要輸出
return {
text,
data,
temp,
idPlus1,
getTest,
addItem,
removeItem,
editItem,
doneEdit
}
}
})
app.mount('#app');
</script>
我只是一棵樹