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

相关推荐
最好结果13 小时前
ruoyi系统-vue-elementui 表格单元格点击复制功能实现:实践与问题解决
vue
叫我阿柒啊1 天前
从Java全栈到前端框架:一次真实的面试对话与技术解析
java·javascript·typescript·vue·springboot·react·前端开发
工业互联网专业2 天前
基于Spark的新冠肺炎疫情实时监控系统_django+spider
python·spark·django·vue·毕业设计·源码·课程设计
SheldonChang2 天前
Onlyoffice集成与AI交互操作指引(Iframe版)
java·人工智能·ai·vue·onlyoffice·postmessage
lichong9512 天前
【混合开发】Android+Webview+VUE播放视频之视频解析工具mediainfo-Macos
android·macos·架构·vue·音视频·api·postman
PBitW2 天前
element plus 使用细节 (二)
前端·vue·element plus·element使用细节
叫我阿柒啊2 天前
从全栈开发到云原生:一位Java工程师的实战经验分享
java·spring boot·redis·云原生·kafka·vue·全栈开发
叫我阿柒啊3 天前
Java全栈工程师的实战面试:从Vue到Spring Boot的技术旅程
java·spring boot·微服务·vue·api·react·rest
刺客-Andy4 天前
CSS中使用 HSL(Hue, Saturation, Lightness) 动态生成色值
前端·css·前端框架·vue