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

相关推荐
FindYou.21 小时前
基于mdEditor实现数据的存储和回显(导出pdf&表情包&目录)
javascript·vue
PD我是你的真爱粉2 天前
Vue3核心语法回顾与Composition深入
前端框架·vue
code袁3 天前
基于Springboot+Vue的家教小程序的设计与实现
vue.js·spring boot·小程序·vue·家教小程序
是梦终空3 天前
计算机毕业设计266—基于Springboot+Vue3的共享单车管理系统(源代码+数据库)
数据库·spring boot·vue·课程设计·计算机毕业设计·源代码·共享单车系统
是梦终空4 天前
计算机毕业设计267—基于Springboot+vue3+小程序的医院挂号系统(源代码+数据库)
spring boot·小程序·vue·毕业设计·课程设计·医院挂号系统·源代码
云游云记4 天前
vue2 vue3 uniapp (微信小程序) v-model双向绑定
微信小程序·uni-app·vue
沐墨染4 天前
黑词分析与可疑对话挖掘组件的设计与实现
前端·elementui·数据挖掘·数据分析·vue·visual studio code
集成显卡5 天前
前端视频播放方案选型:主流 Web 播放器对比 + Vue3 实战
前端·vue·音视频
克里斯蒂亚诺·罗纳尔达5 天前
vue页面加载时间过长优化
vue
草根大哥5 天前
AI编程实践-homex物业管理平台(Go + Vue3 + MySQL 多租户落地)
mysql·golang·vue·ai编程·gin·物业管理系统·多租户