vue3中父子组件通过props 和emit进行通信

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组件,将buttonNamenums作为属性传递给子组件。@showme监听子组件的自定义事件,并在触发时调用increment函数。

在子组件中,我们使用defineProps定义了两个属性:typecounttype是一个String类型的属性,count是一个Number类型的属性,默认值为0。

在模板中,我们使用插值语法显示了props.typeprops.count的值。同时,按钮绑定了点击事件,并通过emit方法触发了名为showme的自定义事件。

这样就完成了父子组件之间的传值,在父组件中点击按钮时,子组件的计数会增加,并更新界面上的显示。请注意,这个示例仅展示了一个简单的父子组件传值的方式,实际应用中可能会更复杂。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值