<template>
<div>
<h1>{{ message }}</h1>
<ChildComponent :count="count" @increment="incrementCount" />
</div>
</template>
<script>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
export default {
name: 'ParentComponent',
components: {
ChildComponent
},
setup() {
const message = 'Hello Vue 3!';
const count = ref(0);
const incrementCount = () => {
count.value++;
};
return {
message,
count,
incrementCount
};
}
};
</script>
<style scoped>
h1 {
color: #42b983;
}
</style>
模板部分 (<template>):
h1 标签,用于显示 message 的值。ChildComponent 组件,并通过属性传递 count,同时监听 increment 事件。脚本部分 (<script>):
ref 函数和 ChildComponent 组件。ParentComponent 的组件。setup 函数中定义了响应式变量 message 和 count,以及方法 incrementCount。样式部分 (<style scoped>):
h1 标签的颜色为绿色。ChildComponent.vue)<template>
<button @click="$emit('increment')">Increment ({{ count }})</button>
</template>
<script>
export default {
name: 'ChildComponent',
props: {
count: Number
}
};
</script>
<style scoped>
button {
padding: 10px 20px;
background-color: #42b983;
color: white;
border: none;
cursor: pointer;
}
</style>
模板部分 (<template>):
increment 事件,并显示当前的 count 值。脚本部分 (<script>):
ChildComponent 的组件。count 的属性。$emit 触发父组件的 increment 事件。样式部分 (<style scoped>):
下一篇:创建一个vue3项目
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站