一、效果
圖1
圖2,點擊報錯之后,又變成圖1的效果
二、使用到了element UI中的以下組件:
<el-button>
<el-input>
三、使用的關鍵點是vue中的v-if指令
四、關鍵代碼如下
HTML部分
1 <div class="content-wrapper"> 2 <div> 3 <el-button type="primary" icon="el-icon-plus" @click.stop="handleShowDialog(0)">添加街道</el-button> 4 <el-button type="primary" icon="el-icon-edit" @click.stop="handleEditStreet">編輯</el-button> 5 <el-button type="primary" icon="el-icon-setting" @click.stop="handleSaveStreet">保存</el-button> 6 </div> 7 <div class="street-wrapper"> 8 <template v-for="(item, index) in streetsData"> 9 <el-button v-if="!isEditStreet" :type="activeButton === index ? 'primary' : 'info'" :key="index" 10 @click.stop="handleButtonClick(index)">{{item.name}}</el-button> 11 <el-input v-else-if="isEditStreet" :key="index" v-model="item.name" style="width:300px;margin-right:5px;margin-bottom:5px;"> 12 <i slot="append" class="remove el-icon-remove"></i> 13 </el-input> 14 </template> 15 </div> 16 </div>
JS部分
1 <script> 2 export default { 3 name: 'official', 4 data () { 5 return { 6 activeButton: 0, 7 dialogTitle: '添加街道', // 控制彈出框title的變量 8 dialogVisible: false, // 彈出框顯示隱藏的控制變量 9 isAddStreet: true, // true表示是添加街道數據,false表示添加的是社區工作站的數據 10 streetNameOrCommunityName: '', // 添加的時候用於保存街道的名稱獲取社區工作站的名稱 11 isEditStreet: false, // 編輯街道 12 isEditCommunity: false, // 編輯社區 13 streetsData: [ 14 {id: 1, name: '觀湖街道'}, 15 {id: 1, name: '民治街道'}, 16 {id: 3, name: '觀瀾街道'}, 17 {id: 4, name: '龍華街道'}, 18 {id: 5, name: '大浪街道'}, 19 {id: 6, name: '福城街道'} 20 ], 21 communityData: [ 22 ] 23 } 24 }, 25 methods: { 26 handleButtonClick (index) { 27 this.activeButton = index 28 }, 29 /** 30 * flag:0表示添加街道,1表示添加社區 31 */ 32 handleShowDialog (flag) { 33 this.isAddStreet = !flag 34 this.dialogTitle = flag ? '添加社區工作站' : '添加街道' 35 this.$nextTick(() => { 36 this.dialogVisible = true 37 }) 38 }, 39 addStreetOrCommunity () { 40 // 校驗輸入的內容不能為空 41 if (!this.streetNameOrCommunityName.length) { 42 this.$message.error('填寫的名稱不能為空或者空字符串') 43 return 44 } 45 // 1.校驗一下當前添加的街道名稱是否已經存在??街道名稱是唯一的 46 // 2.添加成功之后,關閉彈出框,並且要重新請求數據 47 if (this.isAddStreet) { 48 // 調用添加街道的接口 49 this.streetsData.push({id: 10, name: this.streetNameOrCommunityName}) 50 } else { 51 // 調用社區工作站的接口 52 this.communityData.push({id: 10, name: this.streetNameOrCommunityName}) 53 } 54 // 清空streetNameOrCommunityName的數據,避免下次添加的時候顯示上次的數據 55 this.streetNameOrCommunityName = '' 56 this.dialogVisible = false 57 }, 58 handleBeforeClose (done) { 59 this.dialogVisible = false 60 done() 61 }, 62 handleEditCommunity () { 63 this.isEditCommunity = true 64 }, 65 handleSaveCommunity () { 66 this.isEditCommunity = false 67 }, 68 handleEditStreet () { 69 this.isEditStreet = true 70 }, 71 handleSaveStreet () { 72 this.isEditStreet = false 73 }, 74 enterSystem () { 75 this.$router.push('/dashboard') 76 } 77 } 78 } 79 </script>