vue原生实现
以下是 Vue 原生实现常见功能的几种方式,不依赖第三方库:
数据绑定与响应式
使用 data() 返回响应式对象,Vue 自动追踪变化:
export default {
data() {
return {
message: 'Hello Vue'
}
}
}
模板中直接绑定:
<p>{{ message }}</p>
<input v-model="message">
条件渲染
v-if 和 v-show 控制元素显示:
<div v-if="isVisible">条件渲染</div>
<div v-show="isActive">显示控制</div>
列表渲染
v-for 渲染数组或对象:
<li v-for="(item, index) in items" :key="index">
{{ item.text }}
</li>
事件处理
v-on 或 @ 简写绑定事件:
<button @click="handleClick">点击事件</button>
方法定义:
methods: {
handleClick() {
alert('Clicked!')
}
}
计算属性
computed 处理复杂逻辑:
computed: {
reversedMessage() {
return this.message.split('').reverse().join('')
}
}
生命周期钩子
常用钩子示例:
export default {
created() {
console.log('实例创建完成')
},
mounted() {
console.log('DOM挂载完成')
}
}
组件通信
父传子通过 props:
// 父组件
<Child :msg="parentMsg" />
// 子组件
props: ['msg']
子传父通过事件:
// 子组件
this.$emit('notify', data)
// 父组件
<Child @notify="handleNotify" />
动态组件
<component> 配合 is 属性:
<component :is="currentComponent"></component>
插槽
默认插槽和命名插槽:
<!-- 子组件 -->
<slot name="header"></slot>
<slot></slot>
<!-- 父组件 -->
<Child>
<template v-slot:header>标题</template>
<p>默认内容</p>
</Child>
自定义指令
注册全局/局部指令:
// 全局
Vue.directive('focus', {
inserted(el) {
el.focus()
}
})
// 局部
directives: {
focus: {
inserted(el) {
el.focus()
}
}
}
混入 (Mixin)
复用逻辑片段:
const myMixin = {
created() {
this.hello()
},
methods: {
hello() {
console.log('mixin hello')
}
}
}
// 组件中使用
mixins: [myMixin]
过滤器
文本格式化:
filters: {
capitalize(value) {
return value.charAt(0).toUpperCase() + value.slice(1)
}
}
模板使用:

<p>{{ message | capitalize }}</p>
这些实现方式覆盖了 Vue 的核心功能,可根据具体需求选择组合使用。






