效果图:
上代码:
父组件代码:
<template>
<div class="demo01-container">
<div class="parent-sty">
<el-input v-model="name" style="width: 20%;margin-bottom: 2%"/>
<div>子组件点击次数: {{clickCount}}</div>
</div>
<div class="child-sty">
<child-component :name='name' @handleChild='handleChild'/>
</div>
</div>
</template>
<script lang="ts">
/* eslint-disable */
import {Component, Vue} from "vue-property-decorator";
import childComponent from "./child/demo01-child.vue";
@Component({
name: "childParent",
components: {
childComponent
}
})
export default class Demo01 extends Vue {
private firstName: string = "Jone";
private lastName: string = "Doe";
private clickCount: number = 0;
get name() {
return this.firstName + " " + this.lastName;
}
set name(value) {
const splitted = value.split(" ");
this.firstName = splitted[0];
this.lastName = splitted[1] || "";
}
handleChild(count: number): void {
this.clickCount = count;
console.log(this.clickCount);
}
}
</script>
<style scoped lang="sass">
.demo01-container
width: 100%
.parent-sty
width: 100%
height: 200px
border-bottom: 1px solid #cccccc
.child-sty
width: 100%
height: 200px
padding: 2% 0
</style>
子组件代码:
<template>
<div>
<div style="margin-bottom: 2%">父组件传递的值:{{name}}</div>
<el-button type="primary" @click="handleClick">点击传递给父亲</el-button>
</div>
</template>
<script lang="ts">
import {Component, Vue, Prop, Emit} from "vue-property-decorator";
@Component
export default class demo01Child extends Vue {
private count: number = 0;
@Prop({default: ""}) private name!: string; // !: 表示一定存在 ?: 表示可能不存在。这两种在语法上叫赋值断言
handleClick() {
this.count ++;
this.$emit('handleChild', this.count)
}
}
</script>
<style scoped>
</style>