Vue.js中随机生成ID号

Hib*_*RRR 1 vue.js vuex vuetify.js

这是一个为了显示菜谱并对菜谱进行删除、添加、修改等多种操作的项目,但很多时候我需要为其中的每一项都有一个特殊的标识号,但我是手动编写的,因为它是在状态。比如创建一个菜谱的时候,我想为这个菜谱生成一个新的标识号,这里我手动编写。问题是如何在创建每个菜谱时自动生成它?

在这个文件中,我编写了几个对我创建菜谱有用的函数。商店.js:

import Vue from "vue";
import Vuex from "vuex";
import image1 from "../assets/img/image4.jpg";
import image2 from "../assets/img/image2.jpg";
import image3 from "../assets/img/image3.jpg";
import image4 from "../assets/img/insta2.jpg";
Vue.use(Vuex);
export const store = new Vuex.Store({
  state: {
    loadedIngredients: [
      {
        id: '1',
        Name: "Sugar",
        Quantity: "5kg",
      },
      {
        id: "2",
        Name: "Sugar",
        Quantity: "5kg",
      }
    ],
    loadedRecipes: [
      {
        imageUrl: image3,
        id: "3",
        title: "Homemade Burger",
        description:
          "Small plates, salads & sandwiches - an intimate setting with 12 indoor seats plus patio 
           seating.."
      },
      {
        imageUrl: image1,
        id: "1",
        title: "Cake",
        description:
          "Small plates, salads & sandwiches - an intimate setting with 12 indoor seats plus patio 
           seating.."
      },
      {
        imageUrl: image4,
        id: "4",
        title: "Salad",
        description:
          "Small plates, salads & sandwiches - an intimate setting with 12 indoor seats plus patio 
          seating.."
      },
      {
        imageUrl: image2,
        id: "2",
        title: "Kabseh",
        description:
          "Small plates, salads & sandwiches - an intimate setting with 12 indoor seats plus patio 
             seating."
      }
    ],
    user: [
      { name: "Hiba", email: "Hiba69@gmail.com", password: "123442321325" },
    ],
    loading: false,
  },
  actions: {
    updateRecipeData({ commit }, payload) {
      const updateObj = {};
      if (payload.title) {
        updateObj.title == payload.title;
      }
      if (payload.description) {
        updateObj.description == payload.description;
      }
      commit("updateRecipe", payload);
      localStorage.setItem("updateRecipe", this.loadedRecipes);
    },
    updateIngredientData({ commit }, payload) {
      const updateObj = {};
      if (payload.ingredientsQuantity) {
        updateObj.ingredientsQuantity == payload.ingredientsQuantity;
      }
      commit("updateingredient", payload);
      localStorage.setItem("updateingredient", this.loadedIngredients);
    },
  },
  mutations: {
    createRecipe(state, payload) {
      state.loadedRecipes.push(payload);
    },
    createIngredients(state, payload) {
      state.loadedIngredients.push(payload);
    },
    createUser(state, payload) {
      state.user.push(payload);
    },
    delete_recipe(state, id) {
      let index = state.loadedRecipes.findIndex((recipe) => recipe.id == id);
      state.loadedRecipes.splice(index, 1);
      console.log("Deleted Successfully");
    },
    delete_ingredient(state, id) {
      let index = state.loadedIngredients.findIndex(
        (ingredient) => ingredient.id == id
      );
      state.loadedIngredients.splice(index, 1);
      console.log("Deleted Successfully");
    },
    updateRecipe(state, payload) {
      const recipe = state.loadedRecipes.find((recipe) => {
        return recipe.id == payload.id;
      });
      if (payload.title) {
        recipe.title = payload.title;
      }
      if (payload.description) {
        recipe.description = payload.description;
      }
    },
    updateingredient(state,payload) {
      const ingredient = state.loadedingredients.find((ingredient)=>{
        return ingredient.id == payload.id;
      });
      if(payload.ingredientsQuantity){
        ingredient.ingredientsQuantity=payload.ingredientsQuantity
      }
    },
    setLoading(state, payload) {
      state.loading = payload;
    },
  },
  getters: {
    loadedRecipes: (state) => {
      return state.loadedRecipes
        .sort((RecipeA, RecipeB) => {
          return RecipeA.id > RecipeB.id;
        })
        .map((aRec) => {
          aRec["ingredients"] = [...state.loadedIngredients];
          return aRec;
        });
    },
    loadedingredients: (state) => {
      return state.loadedIngredients.sort((ingredientA, ingredientB) => {
        return ingredientA.ingredientsQuantity > ingredientB.ingredientsQuantity;
      });
    },
    featuredRecipes: (getters) => {
      return getters.loadedRecipes.slice(0, 5);
    },
    loadedRecipe: (state) => {
      return (recipeId) => {
        return state.loadedRecipes.find((recipe) => {
          return recipe.id === recipeId;
        });
      };
    },
    loadedingredient: (state) => {
      return (ingredientId) => {
        return state.loadedIngredients.find((ingredient) => {
          return ingredient.id === ingredientId;
        });
      };
    },
    loadedUsers: (state) => {
      return state.user.sort((userA, userB) => {
        return userA.id > userB.id;
      });
    },
    isLoggedIn: (state) => {
      return state.isLoggedIn;
    },
    loading(state) {
      return state.loading;
    },
  },
});
Run Code Online (Sandbox Code Playgroud)

该文件是用于创建配方并向其中输入大量数据的表单。创建菜谱.vue:

<template>
  <v-app>
    <v-container>
      <v-layout row>
        <v-flex xs12 sm6 offset-sm3>
          <h2 class="btn-style">Create Recipe</h2>
        </v-flex>
      </v-layout>
      <v-layout row>
        <v-flex xs12>
          <form @submit.prevent="onCreateRecipe">
              <v-layout>
              <v-flex xs12 sm6 offset-sm3>
                <v-text-field
                  name="id"
                  label="Id"
                  id="id"
                  v-model="id"
                  color="#43A047"
                  required
                >
                </v-text-field>
              </v-flex>
            </v-layout>
            <v-layout>
              <v-flex xs12 sm6 offset-sm3>
                <v-text-field
                  name="title"
                  label="Title"
                  id="title"
                  v-model="title"
                  color="#43A047"
                  required
                >
                </v-text-field>
              </v-flex>
            </v-layout>
            <v-layout>
              <v-flex xs12 sm6 offset-sm3>
                <v-text-field
                  name="imageUrl"
                  label="ImageUrl"
                  id="imageUrl"
                  v-model="imageUrl"
                  color="#43A047"
                  required
                >
                </v-text-field>
              </v-flex>
            </v-layout>
            <v-layout>
              <v-flex xs12 sm6 offset-sm3>
                <img :src="imageUrl" height="300px">
              </v-flex>
            </v-layout>
            <v-layout>
              <v-flex xs12 sm6 offset-sm3>
                <v-text-field
                  name="description"
                  label="Description"
                  id="description"
                  v-model="description"
                  color="#43A047"
                  multi-line
                  required
                >
                </v-text-field>
              </v-flex>
            </v-layout>
            <v-layout>
              <v-flex xs12 sm6 offset-sm3>
                <v-text-field
                  name="ingredientsName"
                  label="IngredientsName"
                  id="ingredientsName"
                  v-model="ingredientsName"
                  color="#43A047"
                  multi-line
                  required
                >
                </v-text-field>
              </v-flex>
            </v-layout>
             <v-layout>
              <v-flex xs12 sm6 offset-sm3>
                <v-text-field
                  name="ingredientsQuantity"
                  label="IngredientsQuantity"
                  id="ingredientsQuantity"
                  v-model="ingredientsQuantity"
                  color="#43A047"
                  multi-line
                  required
                >
                </v-text-field>
              </v-flex>
            </v-layout>
            <v-layout row>
              <v-flex xs12 sm6 offset-sm3>
                <v-btn
                  class="green darken-1 color"
                  :disabled="!formIsValid"
                  type="submit"
                >
                  Create Recipe
                </v-btn>
              </v-flex>
            </v-layout>       
          </form>
        </v-flex>
      </v-layout>
    </v-container>
  </v-app>
</template>
<script> 
export default {
  props:['ingredients'],
  data() {
    return {
      id:"",
      title: "",
      imageUrl: "",
      description: "",
      ingredientsName: "",
      ingredientsQuantity: "",
    };
  },
  computed: {
    formIsValid() {
      return (
        this.id !== ""&&
        this.title !== "" &&
        this.description !== "" &&
        this.imageUrl !== "" &&
        this.ingredientsName !== ""&&
        this.ingredientsQuantity !== ""
      );
    }
  },
  methods: {     
    onCreateRecipe() {
      if (!this.formIsValid) {
        return;
      }
      const recipeData = {
        id:this.id,
        title: this.title,
        description: this.description,
        imageUrl: this.imageUrl,
        ingredientsName:  this.ingredientsName,
        ingredientsQuantity: this.ingredientsQuantity
      };
    // Here we call the setter to put the Data inside it
      this.$store.commit('createRecipe', recipeData)    
      const stringifiedData = JSON.stringify(recipeData);
      // console.log("S: ", stringifiedData);
      localStorage.setItem("recipe", stringifiedData);
      console.log("We got : ", JSON.parse(localStorage.getItem("recipe")));
      // this.$store.dispatch('createRecipe', recipeData).then(() => //alert('STH') or whatever you 
  want to do after you add recipe)    
    },
    addIngredient () {
  this.ingredients = [...this.ingredients , {
    ingredientsName: "",
    ingredientsQuantity: ""
  }]
}     
  }
};    
</script>    
<style scoped>
.btn-style {
  color: #43a047;
}    
.color {
  color: #fafafa;
}
</style>
Run Code Online (Sandbox Code Playgroud)

Moh*_*aza 6

在你的方法->函数onCreateRecipe()->constrecipeData更新id如下

      const recipeData = {
        id: Math.ceil(Math.random()*1000000), //randomly generated id
        title: this.title,
        description: this.description,
        imageUrl: this.imageUrl,
        ingredientsName:  this.ingredientsName,
        ingredientsQuantity: this.ingredientsQuantity
      };
Run Code Online (Sandbox Code Playgroud)