-
什么是组件?
在Vue中,组件是可复用的Vue实例,每个组件都可以拥有自己的模板、脚本和样式。通过组件化,我们可以将页面拆分为多个独立的、可复用的部分,使得代码更易于维护和扩展。 -
创建组件
在Vue 2中,我们可以使用Vue.component()方法来创建全局组件,也可以使用Vue实例中的components选项来注册局部组件。例如:
javascript">// 全局组件
Vue.component('my-component', {// 组件选项
});// 局部组件
new Vue({el: '#app',components: {'my-component': {// 组件选项}}
});
- 组件通信
1.Props(属性):
Props 是父组件向子组件传递数据的一种方式。父组件可以通过在子组件上使用属性的方式传递数据,子组件可以在props选项中声明接收这些数据。例如:
javascript"><!-- 父组件 -->
<template><ChildComponent message="Hello from parent"></ChildComponent>
</template><!-- 子组件 -->
<script>
export default {props: ['message'],mounted() {console.log(this.message);}
}
</script>
2.emit(事件)∗∗:emit是子组件向父组件传递消息的一种方式。子组件可以通过$emit方法触发一个自定义事件,并且可以携带数据。父组件可以监听这个事件,并且接收携带的数据。例如:
javascript">
<!-- 子组件 -->
<template><button @click="sendMessage">Send Message</button>
</template><script>
export default {methods: {sendMessage() {this.$emit('message', 'Hello from child');}}
}
</script><!-- 父组件 -->
<template><ChildComponent @message="handleMessage"></ChildComponent>
</template><script>
export default {methods: {handleMessage(message) {console.log(message); // 输出:Hello from child}}
}
</script>
3.事件总线:
事件总线是一种全局通信的方式,可以用于非父子组件之间的通信。通过创建一个Vue实例作为事件总线,其他组件都可以通过这个实例来触发和监听事件。例如:
javascript">// EventBus.js
import Vue from 'vue';
export const EventBus = new Vue();// 子组件1
import { EventBus } from './EventBus';
export default {methods: {sendMessage() {EventBus.$emit('message', 'Hello from component 1');}}
}// 子组件2
import { EventBus } from './EventBus';
export default {mounted() {EventBus.$on('message', message => {console.log(message); // 输出:Hello from component 1});}
}
- 动态组件
使用动态组件标签:你可以在模板中使用标签,并通过一个特定的属性(例如is)来指定要渲染的组件。这个属性的值可以是一个组件的名称或者一个组件的引用。
javascript"><template><component :is="currentComponent"></component>
</template><script>
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';export default {data() {return {currentComponent: 'ComponentA'};},methods: {toggleComponent() {this.currentComponent = this.currentComponent === 'ComponentA' ? 'ComponentB' : 'ComponentA';}}
}
</script>
5.单文件组件
单文件组件通常包含三个部分:
1.模板(Template):包含组件的HTML结构,使用Vue的模板语法来定义组件的呈现方式。
2.脚本(Script):包含组件的JavaScript逻辑,可以包括组件的数据、方法、生命周期钩子等。
3.样式(Style):包含组件的CSS样式,可以使用普通的CSS或者预处理器(如Sass、Less)来编写。
javascript"><!-- MyComponent.vue -->
<template><div><h1>{{ message }}</h1><button @click="increment">Increment</button></div>
</template><script>
export default {data() {return {message: 'Hello Vue!',count: 0};},methods: {increment() {this.count++;}}
};
</script><style scoped>
h1 {color: blue;
}
button {background-color: green;color: white;
}
</style>