vue实现组件
Vue 组件实现基础
Vue 组件是可复用的 Vue 实例,用于封装 UI 和逻辑。通过 .vue 文件或直接注册组件实现。
单文件组件 (SFC) 示例
<template>
<div class="example-component">
<p>{{ message }}</p>
<button @click="changeMessage">点击修改</button>
</div>
</template>
<script>
export default {
data() {
return {
message: "Hello Vue!"
};
},
methods: {
changeMessage() {
this.message = "Message changed!";
}
}
};
</script>
<style scoped>
.example-component {
color: blue;
}
</style>
全局注册组件
在 main.js 或入口文件中全局注册,所有地方可直接使用:
import ExampleComponent from './components/ExampleComponent.vue';
Vue.component('example-component', ExampleComponent);
局部注册组件
仅在当前组件内可用:
import ExampleComponent from './components/ExampleComponent.vue';
export default {
components: {
'example-component': ExampleComponent
}
};
动态组件
通过 <component :is> 动态切换组件:
<template>
<component :is="currentComponent"></component>
<button @click="toggleComponent">切换组件</button>
</template>
<script>
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';
export default {
data() {
return {
currentComponent: 'ComponentA'
};
},
components: {
ComponentA,
ComponentB
},
methods: {
toggleComponent() {
this.currentComponent = this.currentComponent === 'ComponentA'
? 'ComponentB'
: 'ComponentA';
}
}
};
</script>
Props 数据传递
父组件向子组件传递数据:
<!-- 父组件 -->
<template>
<child-component :title="parentTitle"></child-component>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: { ChildComponent },
data() {
return {
parentTitle: "来自父组件的标题"
};
}
};
</script>
<!-- 子组件 ChildComponent.vue -->
<template>
<h2>{{ title }}</h2>
</template>
<script>
export default {
props: ['title'] // 或使用对象形式定义类型/默认值
};
</script>
事件通信(子 → 父)
子组件通过 $emit 触发父组件事件:
<!-- 子组件 -->
<template>
<button @click="notifyParent">通知父组件</button>
</template>
<script>
export default {
methods: {
notifyParent() {
this.$emit('custom-event', '子组件数据');
}
}
};
</script>
<!-- 父组件 -->
<template>
<child-component @custom-event="handleEvent"></child-component>
</template>
<script>
export default {
methods: {
handleEvent(data) {
console.log(data); // 输出 "子组件数据"
}
}
};
</script>
插槽(Slots)
分发内容到子组件:
<!-- 父组件 -->
<template>
<child-component>
<p>插入到子组件的插槽内容</p>
</child-component>
</template>
<!-- 子组件 -->
<template>
<div>
<slot></slot> <!-- 插槽内容渲染位置 -->
</div>
</template>
生命周期钩子
在组件不同阶段执行逻辑:
export default {
created() {
console.log('组件实例已创建');
},
mounted() {
console.log('DOM 挂载完成');
},
beforeDestroy() {
console.log('组件销毁前');
}
};






