【问题标题】:Clear input in Vue after push to an array推送到数组后清除 Vue 中的输入
【发布时间】:2021-07-05 20:34:20
【问题描述】:

我在 html 中有这个 div,我可以在其中填充输入,然后将该配方保存到数组中。我有一个方法。除此之外,我还有一个搜索字段和一个计算函数来搜索数组上的食谱。但是在我将配方添加到数组后,如果我尝试清除用于放置配方名称的输入,搜索方法会告诉我“无法读取属性 toLowerCase of null”。我不明白为什么我推送到数组的对象会导致模型出现问题。下面是代码,不知道自己解释的好不好。

<div v-show="show_add_receta">
            <p>
                <input type="text" placeholder="id..." v-model="new_receta.id">
            </p>
            <p>
                <input type="text" placeholder="nombre..." v-model="new_receta.nombre">
            </p>
            <p>
                <textarea type="text" placeholder="descripcion..." cols="30" rows="10" v-model="new_receta.descripcion"></textarea>
            </p>
            <p>
                <input type="text" placeholder="chef..." v-model="new_receta.chef">
            </p>
            <p>
                <input type="text" placeholder="ingredientes..." v-model="nuevo_ingrediente" @keyup.enter="AgregarIngrediente()">
            </p>

            <ul>
                <li v-for="ingrediente in new_receta.ingredientes" :key="ingrediente.id"> {{ ingrediente.nombre }} </li>
            </ul>
            <p>
                <button @click="AgregarReceta()">Guardar nueva receta</button>
            </p>
        </div>

这是函数的代码:

    var vm = new Vue({
  el: "#appReceta",
  data: {
    lista_recetas: [
      {
        "id": "001",
        "nombre": "Receta de Tarta de manzana sin azúcar",
        "descripcion": "Descorazona dos de las manzanas y pélalas. Trocea en cubos grandes y ponlos en una olla al fuego con la ramita de canela. Una vez hierva, baja un poco el fuego, tapa la olla y deja cocer entre 20-30 min o hasta que las manzanas estén tiernas.",
        "chef": "Isabel Rescalvo",
        "ingredientes": [
          {
            "id": "i001",
            "nombre": " 3 manzanas grandes",
          },
          {
            "id": "i002",
            "nombre": " 1 rama de canela",
          },
          {
            "id": "i003",
            "nombre": "1 plátano maduro",
          },
        ]
      },
      {
        "id": "002",
        "nombre": "Carlota de mango",
        "descripcion": "Corta la punta de los bizcochos de soletilla sin excederte y guárdala. Recuerda que también puedes hacer la receta de carlota de mango con galletas Marías.",
        "chef": "Isabel Rescalvo",
        "ingredientes": [
          {
            "id": "i004",
            "nombre": "175 gramos de azúcar",
          },
          {
            "id": "i005",
            "nombre": " 2 claras de huevo a temperatura ambiente",
          },
          {
            "id": "i006",
            "nombre": "400 gramos de nata para montar o crema de leche",
          },
          {
            "id": "i007",
            "nombre": "100 gramos de mango troceado",
          },
        ]
      },
      {
        "id": "003",
        "nombre": "Pie de parchita",
        "descripcion": "Tritura las galletas hasta hacerlas polvo en la licuadora o procesadora.",
        "chef": " Dani León.",
        "ingredientes": [
          {
            "id": "i008",
            "nombre": " 3 yemas de huevo",
          },
          {
            "id": "i009",
            "nombre": " 1 lata de leche condensada (397 grs)",
          },
        ]
      },
      {
        "id": "004",
        "nombre": "Dulce de leche reposteroa",
        "descripcion": "Tritura las galletas hasta hacerlas polvo en la licuadora o procesadora.",
        "chef": "Carolina. ",
        "ingredientes": [
          {
            "id": "i010",
            "nombre": " 1 litro de leche entera",
          },
          {
            "id": "i011",
            "nombre": "  300 gramos de azucar (1½ tazas)",
          },
          {
            "id": "i012",
            "nombre": " 1 cucharadita de esencia de vainilla",
          },
        ]
      },
      {
        "id": "005",
        "nombre": "Mermelada de nísperos",
        "descripcion": "Limpia los nísperos, quítales el hueso y la piel..",
        "chef": " Montse Morote Ortega",
        "ingredientes": [
          {
            "id": "i013",
            "nombre": "  1 kilogramo de nísperos sin piel y sin hueso",
          },
          {
            "id": "i014",
            "nombre": " 200 gramos de azúcar (1 taza)",
          },
          {
            "id": "i015",
            "nombre": "1 trozo de limón",
          },
          {
            "id": "i016",
            "nombre": "2 cucharadas soperas de agua",
          },
        ]
      },
    ],
    search: '',
    show_add_receta: false,
    new_receta:{
        "id": "",
        "nombre": "",
        "descripcion": "",
        "chef": "",
        "ingredientes": []
      },
    nuevo_ingrediente: '',
  },
  computed: {
    lista_recetas_filtrada: function () {
      var self = this
      return this.lista_recetas.filter(
        function (value) {
          return value.nombre.toLowerCase().includes(self.search.toLowerCase())
        }
      )
    }
  },
  methods: {
    AgregarIngrediente: function () {
      var new_date = new Date();
      var ingrediente = {
        "id": 'i1000' + new_date.getTime(),
        "nombre": this.nuevo_ingrediente,
      }

      this.new_receta.ingredientes.push(ingrediente);
      this.nuevo_ingrediente = null
    },
    AgregarReceta: function () {
      var receta = this.new_receta;
      this.lista_recetas.push(receta);
      this.new_receta.nombre = null;
      console.log("Agregada")
    }
  }
})

【问题讨论】:

  • 你在哪里清除输入?

标签: javascript vue.js


【解决方案1】:

我添加了resetForm 方法,该方法将在将数据推送到数组demo 后清除表单

为了简单起见,我添加了一些内联样式,显示表单,并添加了新方法,该方法将在数据推送到数组时清除表单。我使用了ES6 Object spread 语法来克隆对象。

例如

let objClone = { ...obj }; // pass all key:value pairs from an object

上面的 sn -p 克隆了obj

<template>
  <div v-show="show_add_receta" style="padding-left: 2rem">
    <p>
      <input type="text" placeholder="id..." v-model="new_receta.id" />
    </p>
    <p>
      <input type="text" placeholder="nombre..." v-model="new_receta.nombre" />
    </p>
    <p>
      <textarea
        type="text"
        placeholder="descripcion..."
        cols="30"
        rows="10"
        v-model="new_receta.descripcion"
      ></textarea>
    </p>
    <p>
      <input type="text" placeholder="chef..." v-model="new_receta.chef" />
    </p>
    <p>
      <input
        type="text"
        placeholder="ingredientes..."
        v-model="nuevo_ingrediente"
        @keyup.enter="AgregarIngrediente()"
      />
    </p>

    <ul>
      <li v-for="ingrediente in new_receta.ingredientes" :key="ingrediente.id">
        {{ ingrediente.nombre }}
      </li>
    </ul>
    <p>
      <button @click="AgregarReceta()">Guardar nueva receta</button>
    </p>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      lista_recetas: [
        {
          id: "001",
          nombre: "Receta de Tarta de manzana sin azúcar",
          descripcion:
            "Descorazona dos de las manzanas y pélalas. Trocea en cubos grandes y ponlos en una olla al fuego con la ramita de canela. Una vez hierva, baja un poco el fuego, tapa la olla y deja cocer entre 20-30 min o hasta que las manzanas estén tiernas.",
          chef: "Isabel Rescalvo",
          ingredientes: [
            {
              id: "i001",
              nombre: " 3 manzanas grandes",
            },
            {
              id: "i002",
              nombre: " 1 rama de canela",
            },
            {
              id: "i003",
              nombre: "1 plátano maduro",
            },
          ],
        },
        {
          id: "002",
          nombre: "Carlota de mango",
          descripcion:
            "Corta la punta de los bizcochos de soletilla sin excederte y guárdala. Recuerda que también puedes hacer la receta de carlota de mango con galletas Marías.",
          chef: "Isabel Rescalvo",
          ingredientes: [
            {
              id: "i004",
              nombre: "175 gramos de azúcar",
            },
            {
              id: "i005",
              nombre: " 2 claras de huevo a temperatura ambiente",
            },
            {
              id: "i006",
              nombre: "400 gramos de nata para montar o crema de leche",
            },
            {
              id: "i007",
              nombre: "100 gramos de mango troceado",
            },
          ],
        },
        {
          id: "003",
          nombre: "Pie de parchita",
          descripcion:
            "Tritura las galletas hasta hacerlas polvo en la licuadora o procesadora.",
          chef: " Dani León.",
          ingredientes: [
            {
              id: "i008",
              nombre: " 3 yemas de huevo",
            },
            {
              id: "i009",
              nombre: " 1 lata de leche condensada (397 grs)",
            },
          ],
        },
        {
          id: "004",
          nombre: "Dulce de leche reposteroa",
          descripcion:
            "Tritura las galletas hasta hacerlas polvo en la licuadora o procesadora.",
          chef: "Carolina. ",
          ingredientes: [
            {
              id: "i010",
              nombre: " 1 litro de leche entera",
            },
            {
              id: "i011",
              nombre: "  300 gramos de azucar (1½ tazas)",
            },
            {
              id: "i012",
              nombre: " 1 cucharadita de esencia de vainilla",
            },
          ],
        },
        {
          id: "005",
          nombre: "Mermelada de nísperos",
          descripcion: "Limpia los nísperos, quítales el hueso y la piel..",
          chef: " Montse Morote Ortega",
          ingredientes: [
            {
              id: "i013",
              nombre: "  1 kilogramo de nísperos sin piel y sin hueso",
            },
            {
              id: "i014",
              nombre: " 200 gramos de azúcar (1 taza)",
            },
            {
              id: "i015",
              nombre: "1 trozo de limón",
            },
            {
              id: "i016",
              nombre: "2 cucharadas soperas de agua",
            },
          ],
        },
      ],
      search: "",
      show_add_receta: true,
      new_receta: {
        id: "",
        nombre: "",
        descripcion: "",
        chef: "",
        ingredientes: [],
      },
      nuevo_ingrediente: "",
    };
  },
  computed: {
    lista_recetas_filtrada: function () {
      var self = this;
      return this.lista_recetas.filter(function (value) {
        return value.nombre.toLowerCase().includes(self.search.toLowerCase());
      });
    },
  },
  methods: {
    AgregarIngrediente: function () {
      var new_date = new Date();
      var ingrediente = {
        id: "i1000" + new_date.getTime(),
        nombre: this.nuevo_ingrediente,
      };

      this.new_receta.ingredientes.push(ingrediente);
      this.nuevo_ingrediente = null;
    },
    resetForm() {
      this.new_receta.id = "";
      this.new_receta.nombre = "";
      this.new_receta.descripcion = "";
      this.new_receta.chef = "";
      this.new_receta.ingredientes = [];
    },
    AgregarReceta: function () {
      this.AgregarIngrediente();

      var receta = { ...this.new_receta };
      this.lista_recetas.push(receta);

      console.log(receta);
      console.log(this.lista_recetas);
      this.resetForm();
    },
  },
};
</script>

<style>
</style>

【讨论】:

  • 非常感谢!!答案是克隆对象。我很痛苦,因为即使我将对象推送到数组之后,如果我在名称字段上写,它在保存的对象中也会发生变化,有点奇怪,但现在我明白了为什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-19
  • 1970-01-01
  • 2021-08-11
  • 1970-01-01
  • 2022-08-23
  • 2021-03-11
  • 2021-11-03
相关资源
最近更新 更多