2016-12-26 5 views
2

나는 a small app that lets you add, remove and edit recipes to a list of recipes입니다.VUE 다목적 구성 요소?

추가 중 경로가 /add이고 편집 중 경로가 /edit입니다. AddRecipe이라는 구성 요소를 사용하고 있습니다. 모두 경로입니다.

경로에 'edit'이 포함되어 있으면 구성 요소가 약간 다르게 동작합니다. 즉, 입력 필드가 편집중인 값으로 미리 채워져 있습니다. 나는이 문제에 더 나은 솔루션이있다 생각하고

<template> 
    <div> 
     <form class="form"> 
      <input v-model="recipe.name" placeholder="Recipe Name"> 
      <textarea v-model="recipe.description" placeholder="Recipe Description..." rows="10"></textarea> 
      <button :disabled="nothingEntered()" @click.prevent="addRecipe">Submit</button> 
     </form> 
    </div> 
</template> 

<script> 
export default { 
    name: 'AddRecipeForm', 
    data() { 
     return { 
      recipe: this.isEdit() 
      ? this.$store.state.recipes[this.$route.params.id] 
      : { 
       name: '', 
       description: '' 
      } 
     } 
    }, 
    methods: { 
     isEdit() { 
      return this.$route.path.includes('edit') 
     }, 
     addRecipe() { 
      if (this.isEdit()) { 
       this.$store.dispatch('addRecipe', this.recipe) 
      } else { 
       this.$store.dispatch('addRecipe', { 
        id: Date.now(), 
        ...this.recipe 
       }) 
      } 
      this.$router.push('/') 
     }, 
     nothingEntered() { 
      return !this.recipe.name || !this.recipe.description 
     } 
    }, 
} 
</script> 

:

여기, 공유 구성 요소 AddRecipeForm.vue입니다. 예를 들어 프로젝트에서 나중에 컴포넌트가 필요한 뷰가 더 많이 있다면? 좋은 깨끗한 읽을 수있는 재사용 가능한 구성 요소를 원한다면 구성 요소의 경로를 계속 확인할 수 없습니다.

동일한보기가 필요한 경로를 처리하는 기본 방법은 무엇입니까?

답변

0

single responsibility에서 보면 클래스 (구성 요소의 경우)를 변경해야하는 2 가지 이유가있는 경우 두 클래스의 기능을 분리해야합니다. 오버로드 된 구성 요소처럼 보일 수 있습니다.

그러나 논리가 포함되어 있으면 현재의 단순성과 관련하여 isEdit과 같은 함수 내에 로직을 래핑 할 수있을 때까지는 좋은 해결책 인 것처럼 보이지만 더 많은 다른 유형의 체크가 그림으로 나오면 두 개 또는 여러 개의 개별 구성 요소를 만들 수 있습니다 AddRecipeForm/EditRecipeForm 등이 각각 하나씩하고 있습니다.

1

if을 너무 많이 가져 오는 경우 일반적인 기술 중 하나는 구성 표 (예 :이 구문을 작성한 것)을 사용하는 것입니다.

data() { 
    return { 
     configMap: { 
      add: { 
       addRecipe: function() {}, 
       inputDisabled: false 
      }, 
      edit: { 
       addRecipe: function() {}, 
       inputDisabled: false 
      }, 
      view: { 
       addRecipe: function() {}, 
       inputDisabled: true 
      } 
     } 
    } 
} 

여기에서 우리는 우리가이 구성 요소에서 직접 사용할 수있는 옵션에 경로 경로의 세그먼트 인 조건을,지도, 그래서 우리는 다음 템플릿 :disabled=configMap[routeType].inputDisabled에 쓸 수 있습니다.

그리고 VUE에서

, 우리는 당신이 위에서했던 것처럼, 더 명확하게 선언 methodscomputed에서 inputDisabled, addRecipe을 배치 할 수 있습니다.

그리고 add의 유형, edit이 노선을 넘어, 우리는 prop으로 유형을 정의하고 그것을 전달할 수

(A 설정 옵션로, 단지 우리와 같은 다른 모든 재사용 구성 요소)

관련 문제