vue實現(xiàn)動態(tài)添加元素(可刪除)
更新時間:2024年12月26日 09:27:07 作者:a伊雪
文章介紹了如何在Vue中動態(tài)添加和刪除元素,通過使用Vue的響應式數據和v-for指令,可以輕松地實現(xiàn)這一功能,文章還詳細講解了如何處理元素的添加和刪除事件,以及如何更新視圖以反映這些變化
vue動態(tài)添加元素(可刪除)
//車輛添加按鈕 handleAddCar(){ console.log(this.infoForm.carList); if(this.infoForm.carList.length>1){ Toast.success({ message:"最多添加兩輛車輛信息" ,duration: 1000}); return; }else{ let cope = { name: "", } this.infoForm.carList.push(cope); } }, //刪除車輛 handleDelCar(index){ this.infoForm.carList.splice(index, 1); },
<van-field placeholder="車輛信息" :disabled="isPreview" v-for="(list,index) in infoForm.carList" :key="index" :label="'車輛信息'+(index+2)" :name="'licenseNum'+(index+2)" v-model="list.name" > <template #button> <van-icon name="close" v-show="!isPreview" size="0.7rem" color="#1989fa" @click="handleDelCar"/> </template> </van-field>
vue動態(tài)添加/刪除dom元素
vue的思想是通過數據操作dom,所以我們根據data中的數據進行對dom的遍歷,從而操作數據就可以對vue進行一個動態(tài)的添加或者刪除啦!
<template> <div> <input v-model="inpValue" type="text" placeholder="請輸入添加文字" @blur="addList" /> <ul v-if="list.length > 0"> <li v-for="(item, index) in list" :key="index"> {{ item }} <span @click="removeList(index)">X</span> </li> </ul> </div> </template>
<script> export default { data() { return { list: [], inpValue: "", }; }, methods: { // 向list數組內添加 addList() { // 判斷輸入框不為空 if (this.inpValue) { // 查重 const isIncludes = this.list.includes(this.inpValue); if (!isIncludes) { this.list.push(this.inpValue); this.inpValue = ""; } else { alert("添加重復"); this.inpValue = ""; } } }, // 向數組中刪除元素 removeList(index) { this.list.splice(index, 1); }, }, }; </script>
<style scoped> div { width: 1200px; margin: 100px auto; } input { width: 400px; border: 1px solid #eee; border-radius: 5px; height: 30px; line-height: 30px; } ul { margin: 20px 0; padding: 0; list-style-type: none; width: 400px; } li { border: 1px solid #ccc; margin: 10px 0; position: relative; } span { position: absolute; cursor: pointer; right: 10px; color: red; } </style>
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
vue-cli3 配置開發(fā)與測試環(huán)境詳解
這篇文章主要介紹了vue-cli3 配置開發(fā)與測試環(huán)境詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-05-05vue實現(xiàn)全屏滾動效果(非fullpage.js)
這篇文章主要為大家詳細介紹了vue實現(xiàn)全屏滾動效果,非fullpage.js,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-03-03