1. v-for문 안에서 v-if를 쓰지 않는다.
이유 : v-for문이 실행 된 후 v-if문이 실행되기 때문에, if문 조건에 따라 분기처리 되는게 아니라 for문을 도는 모든 요소을 다 거치게 된다.
해결 : computed에서 for문을 돌릴 배열을 만들어 그 값을 v-for로 사용한다.
→ 로직과 마크업 코드를 분리하여 가독성 증가
→ 리렌더링 될 때마다 매번 for문이 실행되는게 아니라, computed 값이 바뀌었을 때만 다시 실행될 것이다.
<div v-for='product in cheapProducts'>
computed: {
cheapProducts: () => {
return this.products.filter(function (product) {
return product.price < 100
})
}
}
2. created나 watch에서 methods를 사용하지 않는다.
watch는 값이 변경되야 실행되기 때문에 컴포넌트 처음 초기화 단계에서는 실행되지 않기 때문
그러나 watch에서 method를 사용하여 처음에도 메서드가 실행하게끔 하려면 immediate 속성 사용
methods: {
handleChange() {
// stuff happens
}
},
watch () {
property {
immediate: true // property값이 바뀌지 않아도 컴포넌트 생성되자마자 한번 실행됨
handler() {
this.handleChange()
}
}
}
3. prop의 형식을 지정해준다.
props: {
status: {
type: String,
required: true,
validator: function (value) {
return [
'syncing',
'synced',
'version-conflict',
'error'
].indexOf(value) !== -1
}
}
}
4. 그 외 스타일 가이드 ( 공식문서상 강력권장됨)
1) prop
prop선언시는 camel case, template에서 사용시는 kebab case 사용.
이유 : js에서는 camelCase가 더 자연스럽고, html에서는 kebab-case가 더 자연스럽기 때문
// script
props: {
greetingText: String
}
// template
<WelcomeMessage greeting-text="hi"/>
2) 컴포넌트 파일네임
PascalCase 또는 kebab-case 사용
이유 : 클래스, 생성장 함수 처럼 인스턴스화되서 쓰이는 것이기 때문에 PascalCase사용
이유 : 대소문자가 혼합해 쓰이면 오류날 경우도 있어서 kebab-case도 허용
MyComponent.vue (o) my-component.vue(o) , mycomponent.vue(x) myComponent.vue(x)
3) template에서의 컴포넌트 이름
PascalCase 또는 kebab-case 사용
(pascal이 좀 더 권장됨 : 가독성이 더 좋기때문에, 에디터가 자동으로 완성시켜주기 때문에 )
<MyComponent/>, <my-component></my-component>
4) jsx에서의 컴포넌트 이름
원칙 : camel case
예외 : kebab case - 전역 컴포넌트로 등록할 경우는 kebab 권장
Vue.component('MyComponent', {
// pascal case
})
Vue.component('my-component', {
// 전역으로 등록시는 kebab 권장
})
import MyComponent from './MyComponent.vue'
export default {
name: 'MyComponent',
// ...
}
참고자료
https://betterprogramming.pub/12-vuejs-best-practices-for-pro-developers-28d1f629018c
'프론트엔드 > vue' 카테고리의 다른 글
v-model 에 대해 (0) | 2023.05.12 |
---|---|
v-slot (0) | 2023.05.10 |
data 초기값을 computed로 할 수 없는 이유 (0) | 2023.04.14 |
[vue2] slot (0) | 2023.03.26 |
[vue router] a태그와 router-link의 차이 (0) | 2023.03.26 |