Vue的$set、$delete实现视图层响应
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<title>Document</title>
</head>
<body>
<div id="app">
<div v-for='(item, index) of testArr' :key="index" style="display: flex;">
<p style="margin-right:50px;">{{item.label}}</p>
<el-button type="primary" @click='deleteAct(index)'>删除</el-button>
<el-button type="primary" @click='editAct(item, index)'>修改</el-button>
<el-button type="primary" @click='lookAct(item)'>查看</el-button>
</div>
<el-button type="primary" @click='addAct'>新增</el-button>
<el-dialog
title="新增测试数据"
:visible.sync="dialogVisible"
width="30%"
@closed='closed'>
<el-form ref="form" :model="form" label-width="100px" :rules="rules">
<el-form-item label="数据:" prop='label'>
<el-input v-model="form.label"></el-input>
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer" v-if='notLook'>
<el-button @click='dialogVisible = false'>取 消</el-button>
<el-button type="primary" @click="sure">确 定</el-button>
</span>
</el-dialog>
</div>
</body>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script>
new Vue({
el: '#app',
data: function() {
return {
testArr: [],
dialogVisible: false,
form: {
label: ''
},
rules: {
label: [{ required: true, message: '请输入'}]
},
editIndex: null,
notLook: true
}
},
methods: {
addAct() {
this.dialogVisible = true
},
closed() {
this.$refs.form.resetFields()
this.editIndex = null
this.notLook = true
},
sure() {
this.$refs.form.validate(valid => {
if (valid) {
if(this.editIndex != null) {
this.$set(this.testArr, this.editIndex, {label: this.form.label})
} else {
this.$set(this.testArr, this.testArr.length, {label: this.form.label})
}
this.dialogVisible = false
} else {
return false;
}
})
},
deleteAct(index) {
this.$delete(this.testArr, index)
},
editAct(item, index) {
this.form.label = item.label
this.editIndex = index
this.dialogVisible = true
},
lookAct(item) {
this.form.label = item.label
this.notLook = false
this.dialogVisible = true
}
}
})
</script>
</html>