I'm learning about Vuejs and Element Plus
I tried creating a simple website. Initially there were 2 emails available
When selecting the add button 3 times to add a new email, enter the email in order of empty, valid email, incorrect email format. Then I click submit to validate the email. At the first and third newly added email, an error message appears: "Please enter an email." and "Invalid email format.". This is exactly as I expected. But then when I clicked delete the first newly added email, the order of error messages displayed was no longer correct (it seemed like the last row of messages had disappeared).
Why is this so, how do I fix this problem?
The first image is after adding 3 rows and clicking submit. The second image is to delete the first email line added
<html lang="en">
<head>
<!-- Import style -->
<link rel="stylesheet" href="//unpkg.com/element-plus/dist/index.css" />
<!-- Import Vue 3 -->
<script src="//unpkg.com/vue@3"></script>
<!-- Import component library -->
<script src="//unpkg.com/element-plus"></script>
</head>
<body>
<div id="app">
<el-form :model="form" ref="formName" :rules="rules" label-width="120px">
<el-table :data="form.tableData">
<el-table-column label="Email">
<template #default="scope">
<el-form-item :prop="'tableData.' + scope.$index + '.email'" :rules="rules.email">
<div class="email-row">
<el-input class="email-input" v-model="scope.row.email" placeholder="Enter email"></el-input>
<el-button @click="deleteRow(scope.$index, form.tableData)" type="danger" size="mini">Delete</el-button>
</div>
</el-form-item>
</template>
</el-table-column>
</el-table>
<el-button @click="addRow" type="primary">Add</el-button>
<el-button @click="submit('formName')" type="success">Submit</el-button>
</el-form>
</div>
<script>
const { createApp } = Vue;
const app = createApp({
data() {
return {
form: {
tableData: [
{ email: '[email protected]' },
{ email: '[email protected]' },
],
},
rules: {
email: [
{
validator: (rule, value, callback) => {
if (!value) {
callback(new Error('Please enter an email.'));
} else if (!this.isValidEmail(value)) {
callback(new Error('Invalid email format.'));
} else {
callback();
}
},
trigger: 'submit', // Trigger the validator on submit
},
],
},
};
},
methods: {
isValidEmail(email) {
const re = /^\S+@\S+\.\S+$/;
return re.test(String(email).toLowerCase());
},
addRow() {
this.form.tableData.push({ email: '' });
},
deleteRow(index, rows) {
rows.splice(index, 1);
},
async submit(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
console.log('Form is valid. Submitting...');
}
});
},
},
});
app.use(ElementPlus);
app.mount('#app');
</script>
</body>
</html>

