반응형
Vue.js에서 임의로 ID 번호 생성
이것은 레시피를 전시하고 삭제, 추가, 수정 등 많은 작업을 하기 위한 프로젝트인데, 여러 번 항목별로 특별한 식별번호가 있어야 하는데, 상태 그대로 수작업으로 작성한다.예를 들어, 레시피를 만들 때 이 레시피에 대한 새로운 식별 번호를 생성하려고 하는데, 여기에 수동으로 작성한다.문제는 각 레시피를 만들 때 어떻게 자동으로 생성하느냐 하는 것이다.
이 파일에는 레시피를 만드는 데 유용한 몇 가지 기능을 쓰고 있다.store.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;
},
},
});
이 파일은 레시피를 만들고 거기에 많은 데이터를 입력하기 위한 양식이다.Recrecipe를 만드십시오.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>
menthods -> 함수 onCreateRecrece() -> const recipeData는 다음과 같이 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
};
let random_id = Math.ceil(Math.random()*1000000)
console.log(random_id)
이렇게 하면 0 - 1000000 사이의 임의 ID가 생성됨
참조URL: https://stackoverflow.com/questions/64511668/randomly-generate-id-number-in-vue-js
반응형
'Programing' 카테고리의 다른 글
자바 - C형 포크? (0) | 2022.05.20 |
---|---|
두 집합의 교차점을 계산하는 방법 (0) | 2022.05.19 |
스레드 풀과 함께 MDC를 사용하는 방법 (0) | 2022.05.19 |
vuex와 함께 axios 인스턴스 사용 (0) | 2022.05.19 |
VUE2 하위에서 상위로 매개 변수 전달 (0) | 2022.05.19 |