<template>
  <div>
    <h1>App组件</h1>
    <!-- 在App组件中展示cpn组件的info数据 -->
    <p>{{cpnInfo}}</p>
    <hr>
    <!-- 在App组件中渲染cpn组件 -->
    <cpn @send-info='receiveInfo'></cpn>
  </div>
</template>
<script>
import cpn from './components/cpn.vue'

export default {
  name: 'App',
  components: {
    cpn
  },
  data() {
    return {
      cpnInfo: ''
    }
  },
  methods: {
    receiveInfo(info) {
      // 接收子组件cpn传递的info数据
      this.cpnInfo = info
    }
  }
}
</script> 
<p>// 子组件cpn.vue</p>
<template>
  <div>
    <h2>cpn组件</h2>
    <!-- 在cpn组件中的按钮点击事件中传递info数据给父组件 -->
    <button @click='sendInfo'>传递info数据给父组件</button>
  </div>
</template>
<script>
export default {
  name: 'cpn',
  data() {
    return {
      info: '这是来自cpn组件的info数据'
    }
  },
  methods: {
    sendInfo() {
      // 触发send-info事件,将info数据传递给父组件
      this.$emit('send-info', this.info)
    }
  }
}
</script>
Vue.js 子组件向父组件传递数据示例

原文地址: https://www.cveoy.top/t/topic/mX70 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录