以下是 vue.js 的其他好的和坏的做法:
// good const max_items = 10; function additem(item) { if (items.length <ol> <li> <strong>高效使用 v-for:</strong> <ul> <li>使用 v-for 时,始终提供唯一的键来优化渲染。 </li> </ul> </li> </ol><pre class="brush:php;toolbar:false"> <!-- 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"></basebutton> // bad <button :disabled="isdisabled">{{ 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></baseheader><basecontent></basecontent><basefooter></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 应用程序的质量、可维护性和效率。