Practical Vue.js Development Tips and Optimizations
This article presents a collection of practical Vue.js development techniques, including centralized resize handling, global filter and component registration, route component reuse, lazy-loading strategies, vue-loader configurations, and render-function usage, each illustrated with concise code examples for more efficient and maintainable front-end projects.
Introduction: The author introduces himself and explains that during Vue development many scenarios can be optimized for more efficient and elegant code.
1. Decentralized chart resize handling
General case shows mounting a resize listener in the parent component and calling each chart's resize method.
mounted() {
setTimeout(() => {
window.onresize = () => {
this.$refs.chart1.chartWrapperDom.resize()
this.$refs.chart2.chartWrapperDom.resize()
// ...
}
}, 200)
}
destroyed() { window.onresize = null }Optimization replaces the manual listener with lodash's throttle function.
computed: {
chartWrapperDom() {
const dom = document.getElementById('consume-analy-chart-wrapper')
return dom && Echarts.init(dom)
},
chartResize() {
return _.throttle(() => this.chartWrapperDom && this.chartWrapperDom.resize(), 400)
}
},
mounted() {
window.addEventListener('resize', this.chartResize)
},
destroyed() {
window.removeEventListener('resize', this.chartResize)
}Further optimization extracts the logic into a mixin (mixins/chartInitMixin.js) and reuses it across chart components.
import Echarts from 'echarts'
import _ from 'lodash'
export default {
computed: {
_chartMixin_chartWrapperDom() {
const dom = document.getElementById(this.thisDomId)
return dom && Echarts.init(dom)
},
_chartMixin_chartResize() {
return _.throttle(() => this._chartMixin_chartWrapperDom && this._chartMixin_chartWrapperDom.resize(), 400)
}
},
mounted() {
window.addEventListener('resize', this._chartMixin_chartResize)
},
destroyed() {
window.removeEventListener('resize', this._chartMixin_chartResize)
}
}2. Global filter registration
Instead of defining filters inside each component, a separate file filters/custom.js exports filter functions and the main entry registers them with Vue.filter.
export default {
data () { return {} },
filters: {
orderBy () { /* ... */ },
uppercase () { /* ... */ }
}
}Production code uses
Object.keys(custom).forEach(key => Vue.filter(key, custom[key]))to register all filters at once.
3. Global component registration
Using require.context and a mixin to automatically import and register all components in the components folder.
const requireComponent = require.context('./', true, /\.vue$/)
requireComponent.keys().forEach(filePath => {
const componentConfig = requireComponent(filePath)
const fileName = validateFileName(filePath)
const componentName = fileName.toLowerCase() === 'index'
? capitalizeFirstLetter(componentConfig.default.name)
: fileName
Vue.component(componentName, componentConfig.default || componentConfig)
})4. Route component reuse
When Vue‑router reuses a component on navigation, data may not refresh. Adding a key bound to $route.fullPath forces recreation.
<router-view :key="$route.fullPath"></router-view>5. Component event and attribute passthrough
Using $props, $attrs, and $listeners together with inheritAttrs: false eliminates the need to declare every prop or listener manually.
<input v-bind="$props" @input="$emit('input', $event.target.value)">
<input :value="value" v-bind="$attrs" @input="$emit('input', $event.target.value)">6. Environment‑aware lazy loading
Separate import helpers for development ( _import_development.js) and production ( _import_production.js) allow routes to be eager in dev and lazy in prod.
// _import_production.js
module.exports = file => () => import(`@/views/${file}.vue`)
// _import_development.js
module.exports = file => require(`@/views/${file}.vue`).default7. vue‑loader tricks
Setting preserveWhitespace: false removes unnecessary text nodes, reducing bundle size.
module.exports = {
vue: {
preserveWhitespace: false
}
}Configuring transformToRequire lets image URLs be written directly in templates without manual require calls.
module.exports = {
vue: {
transformToRequire: {
avatar: ['default-src']
}
}
}8. Render function usage
Dynamic tag generation can be simplified with a render function that selects the tag based on a level prop.
Vue.component('child', {
props: { level: { type: Number, required: true } },
render(h) {
const tags = ['div','p','strong','h1','h2','textarea']
const tag = tags[this.level]
return h(tag, this.$slots.default)
}
})Dynamic component selection works similarly by returning h(tag) where tag is a component name such as xixi or haha.
The article concludes with reference links and a promotional block unrelated to the technical content.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Sohu Tech Products
A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
