【问题标题】:Vue JS insert and remove html elements dynamicalyVue JS 动态插入和删除 html 元素
【发布时间】:2018-08-16 15:26:53
【问题描述】:

我想要这样的东西, 如果我点击“Add Another”按钮,另一组输入框应呈现在该组下方,并且该组的“Add Another”按钮应更改为“Remove This学校”,最大输入行数应限制在5。

希望你理解我的要求。我想要的是用户可以输入5所学校或少于5所学校。如果他不小心添加了一些错误信息,他应该有一个删除按钮来删除该记录。我如何实现这一点使用 Vue JS。 这是我的代码。

<template>
  <div id="app">
    <p>Please enter the schools you attained (Maximum five)</p>
    School Name : <input type="text" name="" value="">
    Location  : <input type="text" name="" value="">
    <button type="button" name="button" @click="addAnotherInputBox">Add Another</button>
  </div>
</template>

<script>
export default {
  name: 'app',
  data () {
    return {
      counter:0

    }
  },
  methods:{
    addAnotherInputBox(){

    }
  }
}
</script>

【问题讨论】:

    标签: vue.js vuejs2


    【解决方案1】:

    你去吧,虽然你应该已经填写了添加按钮的逻辑,但你可以自己做

    这是一个有效的小提琴:https://jsfiddle.net/Sletheren/Lo7t0myL/

    <template>
      <div id="app">
        <p>Please enter the schools you attained (Maximum five)</p>
        School Name : <input v-model="name" type="text" name="" value="">
        Location  : <input v-model="location" type="text" name="" value="">
        <button type="button" name="button" @click="addAnotherInputBox">Add Another</button>
        <ul class="schools">
            <li v-for="school in schools">
                {{school.name}} <button @click="removeSchool(school)">remove</button>
            </li>
        </ul>
      </div>
    </template>
    
    <script>
    export default {
      name: 'app',
      data () {
        return {
          counter:0,
          name: '',
          location:'',
          schools: []
        }
      },
      methods:{
        addAnotherInputBox(){
            // your logic here...
           if(this.counter>4){
               alert('you should delete one first! only 5 allowed')
           }else{
                const school = {
                    name: this.name, //name here
                    location: this.location //location here
                }
                this.counter++;
                this.schools.push(school)
                this.name='';
                this.location=''
           }
        },
        removeSchool(school) {
            this.schools.splice(this.schools.indexOf(school),1);
            this.counter--;
        }
      }
    }
    </script>
    

    【讨论】:

    • 非常感谢。我非常感谢您的回答。我从中学到了很多。再次感谢。 =)
    猜你喜欢
    • 1970-01-01
    • 2019-12-29
    • 2017-07-19
    • 2017-02-27
    • 2021-09-26
    • 2018-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多