文章目录
- p11 组件
- 组件的拆分和嵌套
- 组件的CSS作用域
- 组件的通信
- 父子组件的通信
- 父组件传递给子组件
- props的对象用法
- 非prop的attribute
- 子组件传递给父组件
- 案例
p11 组件
组件的拆分和嵌套
推荐安装的VS Cdoe插件
组件的CSS作用域
组件的通信
父子组件的通信
父组件传递给子组件
父组件App.vue
<template>
<show-message-vue title="哈哈哈哈" content="我是哈哈哈"></show-message-vue>
<show-message-vue :title="title" :content="content"></show-message-vue>
<show-message-vue v-bind="message"></show-message-vue>
</template>
<script>
import ShowMessageVue from "./ShowMessage.vue";
export default {
components: {
ShowMessageVue,
},
data() {
return {
title: "嘻嘻嘻",
content: "我是嘻嘻嘻",
message: {
title: "嘿嘿嘿",
content: "我是嘿嘿嘿",
},
};
},
};
</script>
子组件ShowMessage.vue
<template>
<h2>{{ title }}</h2>
<p>{{ content }}</p>
</template>
<script>
export default {
props: ["title", "content"],
};
</script>
props的对象用法
非prop的attribute
子组件传递给父组件
子组件CounterOperation.vue
<template>
<button @click="increment">+1</button>
<button @click="decrement">-1</button>
<input type="text" v-model.number="num" />
<button @click="incrementNum">+n</button>
</template>
<script>
export default {
emits: ["add", "sub", "addNum"],
data() {
return {
num: 0,
};
},
methods: {
increment() {
console.log("+1");
this.$emit("add");
},
decrement() {
console.log("-1");
this.$emit("sub");
},
incrementNum() {
this.$emit("addNum", this.num);
},
},
};
</script>
父组件App.vue
<template>
<h2>{{ counter }}</h2>
<counter-operation-vue
@add="addOne"
@sub="subOne"
@addNum="addNum"
></counter-operation-vue>
</template>
<script>
import CounterOperationVue from "./CounterOperation.vue";
export default {
components: {
CounterOperationVue,
},
data() {
return {
counter: 0,
};
},
methods: {
addOne() {
this.counter++;
},
subOne() {
this.counter--;
},
addNum(num) {
this.counter += num;
},
},
};
</script>
案例
父组件App.vue
<template>
<TopControlVue :titles="titles" @titleClick="titleClick"></TopControlVue>
<h2>{{ content[currentIndex] }}</h2>
</template>
<script>
import TopControlVue from "./TopControl.vue";
export default {
components: {
TopControlVue,
},
data() {
return {
titles: ["衣服", "鞋子", "裤子"],
content: ["衣服页面", "鞋子页面", "裤子页面"],
currentIndex: 0,
};
},
methods: {
titleClick(index) {
this.currentIndex = index;
},
},
};
</script>
子组件TopControl.vue
<template>
<div class="top-control">
<div
class="top-control-item"
:class="{ active: currentIndex === index }"
v-for="(item, index) in titles"
:key="index"
@click="itemClick(index)"
>
<span>{{ item }}</span>
</div>
</div>
</template>
<script>
export default {
emits: ["titleClick"],
props: {
titles: {
type: Array,
default() {
return [];
},
},
},
data() {
return {
currentIndex: 0,
};
},
methods: {
itemClick(index) {
this.currentIndex = index;
this.$emit("titleClick", index);
},
},
};
</script>
<style scoped>
.top-control {
display: flex;
}
.top-control-item {
flex: 1;
text-align: center;
}
.top-control-item.active {
color: red;
}
.top-control-item.active span {
padding: 5px 10px;
border-bottom: 3px solid red;
}
</style>