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点击 就会触发

相关推荐
toooooop81 天前
UniApp Vue2 动态修改 SCSS 伪类颜色
vue
这是个栗子1 天前
微信小程序开发(九)- uni-app微信小程序商城
微信小程序·小程序·uni-app·vue·vuex
鹤鸣的日常2 天前
前端运行时动态环境变量方案
前端·react.js·docker·前端框架·vue·gitlab
来杯@Java3 天前
学生选课管理系统(基于springboot+vue前后端分离的项目)计算机毕业设计java
java·spring boot·spring·vue·毕业设计·maven·mybatis
医疗信息化王工3 天前
医院自律端系统——预警处置模块全栈实战(ASP.NET Core + Vue3 + Quartz 定时调度)
mysql·postgresql·vue·asp.net core·quartz
大大杰哥3 天前
Vue2学习(1)--了解基本方法与概念
javascript·学习·vue
Agatha方艺璇4 天前
前端开发技术复习笔记
vue·bootstrap·css3·html5·web
小葛要努力4 天前
创建vue2项目
程序人生·vue
七仔啊4 天前
基于海康门禁的人员计数系统
vue
步十人5 天前
【Vue3】前置知识简单概述(包括ES6核心语法,模块化ESM以及npm基础)
arcgis·npm·vue·es6