4、插槽(Slots)
插槽允许在父组件中动态地传递内容到子组件的指定位置,提供了更灵活的组件内容定制化
默认插槽
子组件定义了一个插槽,父组件可以通过插槽插入自定义内容
子组件:
<template>
<div>
<slot></slot> <!-- 默认插槽 -->
</div>
</template>
父组件:
<template>
<child-component>
<p>This is custom content passed to the slot</p>
</child-component>
</template>
具名插槽
具名插槽允许你在多个插槽中插入不同的内容
子组件:
<template>
<div>
<slot name="header"></slot>
<slot></slot> <!-- 默认插槽 -->
</div>
</template>
父组件:
<template>
<child-component>
<template v-slot:header>
<h1>This is the header</h1>
</template>
<p>This is the default content</p>
</child-component>
</template>
5、计算属性和方法在组件中的使用
组件内部可以使用计算属性(computed)和方法(methods)来处理数据和逻辑
计算属性:用于从现有数据派生出一个新值,通常是基于响应式数据的派生值 示例:
<template>
<p>{{ fullName }}</p>
</template>
<script>
export default {
data() {
return {
firstName: 'John',
lastName: 'Doe'
};
},
computed: {
fullName() {
return this.firstName + ' ' + this.lastName;
}
}
};
</script>
方法:通常用于处理事件或动态更新数据
示例:
<template>
<button @click="increment">Increment</button>
</template>
<script>
export default {
data() {
return {
count: 0
};
},
methods: {
increment() {
this.count++;
}
}
};
</script>
6、生命周期钩子在组件中的使用
Vue组件中提供了多个生命周期钩子,用于在组件创建、挂载、更新和销毁时执行相应的逻辑
export default {
created() {
console.log('Component Created');
},
mounted() {
console.log('Component Mounted');
},
updated() {
console.log('Component Updated');
},
destroyed() {
console.log('Component Destroyed');
}
};