vue 基础 组件通信1

App.vue

复制代码
<template>
    <div>
        <h3>父组件</h3>
        <p>当前的 num 值:{{ num }}</p>
        <!-- 通过 @increment 监听子组件的 "increment" 事件 -->
        <child-component @increment="numplus" />
    </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
    components: {
        ChildComponent
    },
    data() {
        return {
            num: 0
        }
    },
     methods:{
         numplus() {
             this.num++;
         }
        }
    
}
</script>

ChildComponent.vue

复制代码
<template>
    <div>
        <button @click="increment">增加父组件的num</button>
    </div>
</template>

<script>
export default {
    methods: {
        increment() {
            // 触发自定义事件 "increment"
            this.$emit('increment');
        }
    }
}
</script>
创建子组件

1首先要引入组件

2注册组件

3,拿注册的组件当标签在template中div盒子中使用

子组件当中

html 复制代码
<template>
    <div>
        <button @click="increment">增加父组件的num</button>
    </div>
</template>
javascript 复制代码
export default {
    methods: {
        increment() {
            // 触发自定义事件 "increment"
            this.$emit('increment');
        }
    }
}

this.$emit('increment');用于与父组件进行通信。

父组件当中

html 复制代码
<child-component @increment="numplus" />

子组件当中的button点击 就会触发

相关推荐
澄江静如练_25 分钟前
ref和reactive
vue
码界筑梦坊1 天前
336-基于Python的肺癌数据可视化分析预测系统
开发语言·python·信息可视化·数据分析·django·vue·毕业设计
Thomas.Sir1 天前
第十四章:基于 FastAPI+Vue3 的智能聊天系统全栈开发实战
vue·状态模式·fastapi·智能
abigale032 天前
从零实现 AI 聊天助手:可直接复用的前端核心方案
chatgpt·vue·流式输出
前端飞行手册3 天前
electron应用开发模板,集成多种解决方案
前端·javascript·学习·electron·前端框架·vue
RuoyiOffice4 天前
企业请假销假系统设计实战:一张表、一套流程、两段生命周期——BPM节点驱动的表单变形术
java·spring·uni-app·vue·产品运营·ruoyi·anti-design-vue
Mephisto1805024 天前
Vue 3 变量声明和调用
vue
RuoyiOffice4 天前
SpringBoot+Vue3+Uniapp实现PC+APP双端考勤打卡设计:GPS围栏/内网双模打卡、节假日方案、定时预生成——附数据结构和核心源码讲解
java·spring·小程序·uni-app·vue·产品运营·ruoyi
Irene19914 天前
Vue 2、Vue 3 、Vuex 3、Vuex 4 和 Pinia 响应式丢失场景及解决方案
vue·pinia·vuex
Java陈序员5 天前
自建 Claude Code 镜像!一站式开源中转服务!
docker·node.js·vue·claude·claude code