以下是 Vue.js 的其他好的和坏的做法:
// Good const MAX_ITEMS = 10; function addItem(item) { if (items.length < MAX_ITEMS) { items.push(item); } } // Bad function addItem(item) { if (items.length < 10) { items.push(item); } }
<!-- Good --> <div v-for="item in items" :key="item.id"> {{ item.name }} </div> <!-- Bad --> <div v-for="item in items"> {{ item.name }} </div>
<!-- Good --> <div class="item">{{ item.name }}</div> <style scoped> .item { color: red; } </style> <!-- Bad --> <div :style="{ color: 'red' }">{{ item.name }}</div>
// Good <BaseButton :label="buttonLabel" :disabled="isDisabled" @click="handleClick" /> // Bad <button :disabled="isDisabled" @click="handleClick">{{ buttonLabel }}</button>
// Good props: { title: { type: String, required: true }, age: { type: Number, default: 0 } } // Bad props: { title: String, age: Number }
// Good methods: { fetchData() { this.fetchUserData(); this.fetchPostsData(); }, async fetchUserData() { ... }, async fetchPostsData() { ... } } // Bad methods: { async fetchData() { const userResponse = await fetch('api/user'); this.user = await userResponse.json(); const postsResponse = await fetch('api/posts'); this.posts = await postsResponse.json(); } }
// Good computed: { fullName() { return `${this.firstName} ${this.lastName}`; } } // Bad computed: { fetchData() { // Side effect: fetch data inside a computed property this.fetchUserData(); return this.user; } }
<!-- Good: Use v-show for toggling visibility --> <div v-show="isVisible">Content</div> <!-- Good: Use v-if for conditional rendering --> <div v-if="isLoaded">Content</div> <!-- Bad: Use v-if for simple visibility toggling --> <div v-if="isVisible">Content</div>
<!-- Good: Small, focused template --> <template> <div> <BaseHeader /> <BaseContent /> <BaseFooter /> </div> </template> <!-- Bad: Large, monolithic template --> <template> <div> <header>...</header> <main>...</main> <footer>...</footer> </div> </template>
// Good // store.js export default new Vuex.Store({ state: { user: {} }, mutations: { setUser(state, user) { state.user = user; } }, actions: { async fetchUser({ commit }) { const user = await fetchUserData(); commit('setUser', user); } } });
// Good methods: { updateUser() { this.$store.commit('setUser', newUser); } } // Bad methods: { updateUser() { this.$store.state.user = newUser; // Direct mutation } }
Vue.config.errorHandler = function (err, vm, info) { console.error('Vue error:', err); };
// Good methods: { async fetchData() { try { const data = await fetchData(); this.data = data; } catch (error) { this.errorMessage = 'Failed to load data. Please try again.'; } } } // Bad methods: { async fetchData() { try { this.data = await fetchData(); } catch (error) { console.error('Error fetching data:', error); } } }
通过遵循这些额外的实践,您可以进一步提高 Vue.js 应用程序的质量、可维护性和效率。
以上是Vue js 的通用编码标准。的详细内容。更多信息请关注PHP中文网其他相关文章!