vue实现的工具
以下是基于 Vue 实现常见工具的几种方法和示例:
自定义表单组件
使用 Vue 的 v-model 实现双向绑定的表单控件,例如输入框增强组件:
<template>
<input
:value="modelValue"
@input="$emit('update:modelValue', $event.target.value)"
:placeholder="placeholder"
/>
</template>
<script>
export default {
props: ['modelValue', 'placeholder'],
emits: ['update:modelValue']
}
</script>
模态框工具
通过 v-if 和插槽实现可复用的模态对话框:
<template>
<div class="modal-mask" v-if="show">
<div class="modal-container">
<slot name="header"></slot>
<slot name="body"></slot>
<button @click="$emit('close')">关闭</button>
</div>
</div>
</template>
<script>
export default {
props: ['show'],
emits: ['close']
}
</script>
数据可视化工具
结合 ECharts 实现图表组件:
<template>
<div ref="chartDom" style="width: 600px;height:400px;"></div>
</template>
<script>
import * as echarts from 'echarts';
export default {
props: ['options'],
mounted() {
this.chart = echarts.init(this.$refs.chartDom);
this.chart.setOption(this.options);
},
watch: {
options(newVal) {
this.chart.setOption(newVal);
}
}
}
</script>
状态管理工具
使用 Vue 的 provide/inject 实现简易状态管理:
// store.js
import { reactive, provide, inject } from 'vue';
export const createStore = () => {
const state = reactive({ count: 0 });
const increment = () => state.count++;
provide('store', { state, increment });
};
export const useStore = () => {
return inject('store');
};
路由导航工具
实现基础路由功能:
// router.js
import { ref } from 'vue';
export const createRouter = (routes) => {
const currentPath = ref(window.location.hash.slice(1) || '/');
window.addEventListener('hashchange', () => {
currentPath.value = window.location.hash.slice(1);
});
return {
currentPath,
routes
};
};
工具函数库
创建可复用的工具函数组合:

// utils.js
import { ref, computed } from 'vue';
export function useDebounce(value, delay = 300) {
const debouncedValue = ref(value);
let timeout;
watch(() => value, (newVal) => {
clearTimeout(timeout);
timeout = setTimeout(() => {
debouncedValue.value = newVal;
}, delay);
});
return debouncedValue;
}
注意事项
- 组件设计应遵循单一职责原则
- 复杂工具建议拆分为多个组件组合
- 使用
props和emits明确数据流向 - 考虑使用 Composition API 提高逻辑复用性






