<div id="app">
  <form>
    <label>班级:</label>
    <input type="text" v-model="newStudent.grade">
    <label>姓名:</label>
    <input type="text" v-model="newStudent.name">
    <label>性别:</label>
    <input type="text" v-model="newStudent.gender">
    <label>年龄:</label>
    <input type="text" v-model="newStudent.age">
    <button type="button" @click.prevent="addOrUpdateStudent">确认{{selectedIndex === null ? '添加' : '修改'}}</button>
    <button type="button" @click.prevent="reset">重置表单</button>
  </form>
  <table border="1" width="50%" style="border-collapse: collapse;">
    <tr>
      <th>班级</th>
      <th>姓名</th>
      <th>性别</th>
      <th>年龄</th>
      <th>操作</th>
    </tr>
<pre><code>&lt;tr align=&quot;center&quot; v-for=&quot;(item, index) in students&quot;&gt;
  &lt;td&gt;{{item.grade}}&lt;/td&gt;
  &lt;td&gt;{{item.name}}&lt;/td&gt;
  &lt;td&gt;{{item.gender}}&lt;/td&gt;
  &lt;td&gt;{{item.age}}&lt;/td&gt;
  &lt;td&gt;
    &lt;button type=&quot;button&quot; @click.prevent=&quot;editStudent(index)&quot;&gt;修改&lt;/button&gt;
    &lt;button type=&quot;button&quot; @click.prevent=&quot;delStudent(index)&quot;&gt;删除&lt;/button&gt;
  &lt;/td&gt;
&lt;/tr&gt;
</code></pre>
  </table>
</div>
<script type="text/javascript">
  let vm=new Vue ({
    el:'#app',
    data:{
      students:[],
      newStudent:{
        grade:'',
        name:'',
        gender:'',
        age:''
      },
      selectedIndex: null
    },
    
    methods:{
      addOrUpdateStudent(){
        if(this.selectedIndex === null) {
          this.students.push(this.newStudent);
        } else {
          this.students.splice(this.selectedIndex, 1, this.newStudent);
        }
        this.reset();
      },
      editStudent(index) {
        this.newStudent = Object.assign({}, this.students[index]);
        this.selectedIndex = index;
      },
      delStudent(index){
        this.students.splice(index, 1);
      },
      reset() {
        this.newStudent = {
          grade:'',
          name:'',
          gender:'',
          age:''
        };
        this.selectedIndex = null;
      }
    }
    
  })
</script>
学生信息管理系统 - Vue.js 实现

原文地址: https://www.cveoy.top/t/topic/nQtX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录