vue快速入门(三十六)组件通信-子传父

注释很详细,直接上代码

上一篇

新增内容

  1. 子传父之子组件传递方法与值
  2. 子传父之父组件接收方法与值
    源码

App.vue

html 复制代码
<template>
  <div id="app">
    <!-- @事件名="方法" 接收子组件传递过来的方法,
      可在方法中使用子组件传递的值 -->
    <MyTest :counts="counts" @addCount="addCount"/>
  </div>
</template>
<script>
// 导入局部注册组件
import MyTest from "./components/MyTest.vue";
export default {
  name: "App",
  components: {
    //注册局部注册组件
    MyTest,
  },
  data() {
    return {
      //定义data值
      counts:1000
    };
  },
  methods: {
    addCount(num){//使用子组件传递过来的值进行操作
      this.counts+=num;
    }
  },
};
</script>
<style>
#app {
  display: flex;
  flex-direction: row;
}
</style>

MyTest.vue

html 复制代码
<template>
    <div id="MyTest">
        
       <h1>当前功德数:{{ counts }}</h1>
       <div>
        <!-- @click="$emit(事件名',传的数据) ,向父组件发送事件并传值" -->
       <button v-for="(item) in num" @click="$emit('addCount',item)" :key="item">敲木鱼{{ item }}次</button>
       </div>
    </div>
</template>

<script>
    export default {
        // 因为组件每次使用都需要是一个新的对象,
        // 所以data数据都需要是函数返回
        data() {
            return {
                num:[1,10,100]
            }
        },
        // 接收父组件传过来的数据
        props:['counts']
    }
</script>

<style lang="less" scoped>
#MyTest button{
    margin: 0 10px;
}

</style>

效果演示

相关推荐
i220818 Faiz Ul1 天前
计算机毕业设计|基于springboot + vue鲜花商城系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
暴力袋鼠哥1 天前
基于 Spring Boot 3 + Vue 3 的农产品在线销售平台设计与实现
vue.js·spring boot·后端
coding随想1 天前
TypeScript 高级类型全攻略:从“可表达性”到“类型体操”的实践之路
前端·javascript·typescript
WWWWW先生1 天前
02 登录功能实现
前端·javascript
Lee川1 天前
深入解析:从内存模型到作用域陷阱——JavaScript变量的前世今生
javascript·算法
豆苗学前端1 天前
彻底讲透医院移动端手持设备PDA离线同步架构:从"记账本"到"分布式共识",吊打面试官
前端·javascript·后端
paterWang1 天前
基于SpringBoot+Vue的鞋类商品购物商城系统的设计与实现
vue.js·spring boot·后端
Esaka_Forever1 天前
Promise resolve 的基础用法
前端·javascript
赵_叶紫2 天前
Vue 3 从基础到组合式 API 全解析
vue.js