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

相关推荐
REDcker1 小时前
浏览器端Web程序性能分析与优化实战 DevTools指标与工程清单
开发语言·前端·javascript·vue·ecmascript·php·js
jay神1 天前
基于团队模式的C程序设计课程辅助教学管理系统
java·spring boot·vue·web开发·管理系统
钛态1 天前
前端TypeScript高级技巧:让你的代码更安全
前端·vue·react·web
吴声子夜歌3 天前
Vue3——路由管理
前端·vue·es6·vue-router
钛态3 天前
前端微前端架构:大项目的救命稻草还是自找麻烦?
前端·vue·react·web
钛态3 天前
前端趋势:别被时代抛弃
前端·vue·react·web
恶猫3 天前
网页自动化模拟操作时,模拟真实按键触发事件【终级方案】
前端·javascript·自动化·vue·网页模拟
无心使然云中漫步4 天前
Openlayers调用ArcGis地图服务之五 —— 要素识别(/identify)
前端·arcgis·vue·数据可视化
蜡台4 天前
H5入住浙里办App详细步骤
vue·uniapp·h5·浙政钉
呱牛do it4 天前
企业级门户网站设计与实现:基于SpringBoot + Vue3的全栈解决方案(Day 7)
java·vue