vue中的父子组件
在vue 3中可以使用组件的方式创建父子组件,并通过props和emit来进行父子组件的通信
下面是一个简单示例,展示了在vue3中创建父子组件并进行调用:
父组件
<!-- BlogPost.vue -->
<script setup>
import { ref } from 'vue';
import ChildProrsConmponents from './ChildProrsConmponents.vue';
const buttonName=ref('新增')
function insert(){
alert("新增")
}
function del(){
alert("删除")
}
function update(){
alert("更新")
}
function show(){
alert("子组件的自定义方法被调用")
}
</script>
<template>
<ChildProrsConmponents :type="buttonName" @showme="show($event)"/>
<ChildProrsConmponents :type="buttonName"
@click="insert"/>
<ChildProrsConmponents type="删除"
@click="del"/>
<ChildProrsConmponents type="更新"
@click="update"/>
</template>
子组件
<script setup>
import { defineProps, ref ,reactive} from 'vue';
const isActive = ref(false);
if (props.type == '新增') {
isActive.value = true
}
const props = defineProps({
type: String //设置传值类型,可设置多个值
})
</script>
<template>
<!-- <button :class="{ 'insertButton': isActive }">
{{ props.type }}</button> -->
<button :class="{'insertButton': isActive}"
@click="$emit('showme',nums)">
{{ props.type }}</button>
</template>
<style scoped>
button {
width: 80px;
height: 30px;
border: 0;
border-radius: 3px;
}
.insertButton {
background-color: aquamarine;
}
.deletebutton {
background-color: black;
}
</style>
也可以这样写
在Vue 3中,可以使用组合式API来实现父子组件之间的传值。以下是一个示例:
父组件:
<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
const buttonName = ref('新增');
const nums = ref(0);
function increment() {
nums.value++;
}
</script>
<template>
<ChildComponent :type="buttonName" :count="nums" @showme="increment" />
</template>
子组件:
<script setup>
import { defineProps, emit } from 'vue';
const props = defineProps({
type: String,
count: {
type: Number,
default: 0
}
});
function handleClick() {
emit('showme');
}
</script>
<template>
<button @click="handleClick">{{ props.type }} ({{ props.count }})</button>
</template>
在父组件中,我们通过ref
创建了一个名为buttonName
的响应式变量,并初始化为字符串"新增"。还创建了一个名为nums
的响应式变量,并初始化为0。increment
函数用于增加nums
的值。
在模板中,我们使用ChildComponent
组件,将buttonName
和nums
作为属性传递给子组件。@showme
监听子组件的自定义事件,并在触发时调用increment
函数。
在子组件中,我们使用defineProps
定义了两个属性:type
和count
。type
是一个String类型的属性,count
是一个Number类型的属性,默认值为0。
在模板中,我们使用插值语法显示了props.type
和props.count
的值。同时,按钮绑定了点击事件,并通过emit
方法触发了名为showme
的自定义事件。
这样就完成了父子组件之间的传值,在父组件中点击按钮时,子组件的计数会增加,并更新界面上的显示。请注意,这个示例仅展示了一个简单的父子组件传值的方式,实际应用中可能会更复杂。