簡體   English   中英

推送到數組后清除 Vue 中的輸入

[英]Clear input in Vue after push to an array

我在 html 中有這個 div,我可以在其中填充輸入,然后將該配方保存到數組中。 我有一個方法。 除此之外,我還有一個搜索字段和一個計算出來的 function 來搜索數組上的食譜。 但是在我將菜譜添加到數組后,如果我嘗試清除用於放置菜譜名稱的輸入,搜索方法會告訴我“無法讀取屬性 toLowerCase of null”。 我不明白為什么我推送到陣列的 object 會導致 model 出現問題。 下面是代碼,不知道自己解釋的好不好。

<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")
    }
  }
})

我添加了resetForm方法,該方法將在數據推送到數組演示后清除表單

為了簡單起見,我添加了一些內聯樣式,顯示表單,並添加了新方法,該方法將在數據推送到數組時清除表單。 我使用了ES6 Object 擴展語法來克隆 object。

例如

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

上面的代碼片段克隆了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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM