Vue前端开发规范整理(推荐)(5)
反例:
<input v-bind:value="newTodoText" :placeholder="newTodoInstructions" >
三、推荐
1. 单文件组件的顶级元素的顺序
单文件组件应该总是让<script>、<template> 和 <style> 标签的顺序保持一致。且 <style> 要放在最后,因为另外两个标签至少要有一个。
正例:
<!-- ComponentA.vue --> <template>...</template> <script>/* ... */</script> <style>/* ... */</style>
四、谨慎使用 (有潜在危险的模式)
1. 没有在 v-if/v-if-else/v-else 中使用 key
如果一组 v-if + v-else 的元素类型相同,最好使用 key (比如两个 <div> 元素)。
正例:
<div
v-if="error"
key="search-status"
>
错误:{{ error }}
</div>
<div
v-else
key="search-results"
>
{{ results }}
</div>
反例:
<div v-if="error">
错误:{{ error }}
</div>
<div v-else>
{{ results }}
</div>
2. scoped 中的元素选择器
元素选择器应该避免在 scoped 中出现。
在 scoped 样式中,类选择器比元素选择器更好,因为大量使用元素选择器是很慢的。
正例:
<template>
<button class="btn btn-close">X</button>
</template>
<style scoped>
.btn-close {
background-color: red;
}
</style>
反例:
<template>
<button>X</button>
</template>
<style scoped>
button {
background-color: red;
}
</style>
3. 隐性的父子组件通信
应该优先通过 prop 和事件进行父子组件之间的通信,而不是 this.$parent 或改变 prop。
正例:
Vue.component('TodoItem', {
props: {
todo: {
type: Object,
required: true
}
},
template: `
<input
:value="todo.text"
@input="$emit('input', $event.target.value)"
>
`
})
反例:
Vue.component('TodoItem', {
props: {
todo: {
type: Object,
required: true
}
},
methods: {
removeTodo () {
var vm = this
vm.$parent.todos = vm.$parent.todos.filter(function (todo) {
return todo.id !== vm.todo.id
})
}
},
template: `
<span>
{{ todo.text }}
<button @click="removeTodo">
X
</button>
</span>
`
})
4. 非 Flux 的全局状态管理
应该优先通过 Vuex 管理全局状态,而不是通过 this.$root 或一个全局事件总线。
