js实现vue组件
Vue 组件的基本实现
在 JavaScript 中实现 Vue 组件可以通过 Vue.js 的选项式 API 或组合式 API 来完成。以下分别展示两种方式的实现方法。
选项式 API 实现
// 定义一个 Vue 组件
const MyComponent = {
template: `
<div>
<h1>{{ title }}</h1>
<button @click="increment">点击计数: {{ count }}</button>
</div>
`,
data() {
return {
title: 'Vue 组件示例',
count: 0
}
},
methods: {
increment() {
this.count++
}
}
}
// 注册组件
Vue.component('my-component', MyComponent)
// 创建 Vue 实例
new Vue({
el: '#app'
})
组合式 API 实现 (Vue 3)
// 使用组合式 API 定义组件
const { createApp, ref } = Vue
const MyComponent = {
template: `
<div>
<h1>{{ title }}</h1>
<button @click="increment">点击计数: {{ count }}</button>
</div>
`,
setup() {
const title = 'Vue 组件示例'
const count = ref(0)
const increment = () => {
count.value++
}
return {
title,
count,
increment
}
}
}
// 创建应用并挂载
const app = createApp({
components: {
MyComponent
}
})
app.mount('#app')
单文件组件 (SFC) 实现
在实际项目中,通常会使用单文件组件 (.vue 文件) 的方式组织代码:
<template>
<div>
<h1>{{ title }}</h1>
<button @click="increment">点击计数: {{ count }}</button>
</div>
</template>
<script>
export default {
data() {
return {
title: 'Vue 组件示例',
count: 0
}
},
methods: {
increment() {
this.count++
}
}
}
</script>
<style scoped>
h1 {
color: #42b983;
}
</style>
组件通信方式
父组件向子组件传递数据 (Props)
// 子组件
const ChildComponent = {
props: ['message'],
template: '<div>接收的消息: {{ message }}</div>'
}
// 父组件
const ParentComponent = {
components: { ChildComponent },
template: '<child-component message="来自父组件的消息"></child-component>'
}
子组件向父组件发送事件 (Emit)
// 子组件
const ChildComponent = {
template: `
<button @click="sendMessage">发送消息</button>
`,
methods: {
sendMessage() {
this.$emit('message-sent', '来自子组件的消息')
}
}
}
// 父组件
const ParentComponent = {
components: { ChildComponent },
template: `
<child-component @message-sent="handleMessage"></child-component>
`,
methods: {
handleMessage(msg) {
console.log('收到消息:', msg)
}
}
}
生命周期钩子
Vue 组件提供了一系列生命周期钩子,可以在不同阶段执行自定义逻辑:
const LifecycleDemo = {
template: '<div>生命周期示例</div>',
beforeCreate() {
console.log('beforeCreate')
},
created() {
console.log('created')
},
beforeMount() {
console.log('beforeMount')
},
mounted() {
console.log('mounted')
},
beforeUpdate() {
console.log('beforeUpdate')
},
updated() {
console.log('updated')
},
beforeDestroy() {
console.log('beforeDestroy')
},
destroyed() {
console.log('destroyed')
}
}
动态组件
Vue 支持动态切换不同组件:
const ComponentA = { template: '<div>组件A</div>' }
const ComponentB = { template: '<div>组件B</div>' }
const App = {
components: { ComponentA, ComponentB },
data() {
return {
currentComponent: 'ComponentA'
}
},
template: `
<div>
<button @click="currentComponent = 'ComponentA'">显示A</button>
<button @click="currentComponent = 'ComponentB'">显示B</button>
<component :is="currentComponent"></component>
</div>
`
}
以上示例展示了 Vue 组件的基本实现方式,包括组件定义、通信、生命周期和动态组件等核心功能。根据项目需求,可以选择选项式 API 或组合式 API 进行开发。







