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

相关推荐
duansamve4 小时前
Vue3与Vue2中使用对比
vue
Jeffrey__Lin2 天前
解决ElementPlus使用ElMessageBox.confirm,出现层级低于el-table的问题
前端·javascript·elementui·vue·elementplus
麦麦大数据2 天前
F024 RNN+Vue+Flask电影推荐可视化系统 python flask mysql 深度学习 echarts
python·rnn·深度学习·vue·echarts·电影推荐
HECHEN****3 天前
Composition API 与 React Hook 很像,区别是什么?
vue·面试题
知识分享小能手3 天前
微信小程序入门学习教程,从入门到精通,项目实战:美妆商城小程序 —— 知识点详解与案例代码 (18)
前端·学习·react.js·微信小程序·小程序·vue·前端技术
cgsthtm3 天前
RuoYi.Net后端返回雪花ID前端精度丢失问题
oracle·vue·精度丢失·雪花id·ruoyi.net
玩代码3 天前
使用 nvm(Node Version Manager) 高效管理Node.js
node.js·vue·nvm
bdawn4 天前
Vue3 项目首屏加载性能优化全攻略
性能优化·vue·策略·分包
Orange_sparkle4 天前
若依使用基本步骤
java·vue
肖祥4 天前
uni-app x封装request,统一API接口请求
vue