Vue组件实现方法
Vue组件实现方法
选项式API(Options API)
使用data、methods、props等选项定义组件,适合传统Vue 2.x项目或偏好结构化代码的场景。
<template>
<div>{{ message }}</div>
</template>
<script>
export default {
data() {
return {
message: 'Hello Vue!'
}
},
methods: {
updateMessage() {
this.message = 'Updated'
}
}
}
</script>
组合式API(Composition API)
通过setup()函数组织逻辑,适合Vue 3.x的复杂组件,支持更好的代码复用和类型推断。
<template>
<div>{{ count }}</div>
<button @click="increment">+1</button>
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
const count = ref(0)
const increment = () => count.value++
return { count, increment }
}
}
</script>
单文件组件(SFC)
.vue文件包含<template>、<script>和<style>三部分,是Vue推荐的组件封装方式。
<template>
<button class="btn">{{ label }}</button>
</template>
<script>
export default {
props: ['label']
}
</script>
<style scoped>
.btn {
color: red;
}
</style>
函数式组件
无状态组件,通过渲染函数(render function)直接返回虚拟DOM,适用于纯展示型组件。
export default {
functional: true,
render(h, { props }) {
return h('div', props.text)
}
}
动态组件
使用<component :is>实现运行时切换组件,常用于标签页或条件渲染场景。
<template>
<component :is="currentComponent" />
</template>
<script>
import CompA from './CompA.vue'
import CompB from './CompB.vue'
export default {
data() {
return {
currentComponent: 'CompA'
}
}
}
</script>
异步组件
通过defineAsyncComponent实现按需加载,优化应用启动性能。
import { defineAsyncComponent } from 'vue'
const AsyncComp = defineAsyncComponent(() => import('./Comp.vue'))
递归组件
组件调用自身实现树形结构,需设置name选项并添加终止条件。
<template>
<div>
{{ node.name }}
<TreeNode v-for="child in node.children" :node="child" />
</div>
</template>
<script>
export default {
name: 'TreeNode',
props: ['node']
}
</script>






