027.Vue3入门,父页面接收子页面传过来的事件和参数

1、App.vue代码:

<template>
  <Father/>
</template>

<script setup>
import Father from './view/Father.vue'
</script>

<style>
</style>

2、Father.vue代码:

<template>
  <h3>父页面</h3>
  <Child @myEvent="GetHandle"/>
  <p>父元素接收: {{ msg }}</p>
</template>

<script>
import Child from './Child.vue';

export default {
  data() {
    return {
      msg: ''
    }
  },
  components: {
    Child
  },
  methods: {
    GetHandle(data) {
      console.log('父页面被触发,参数:', data);
      this.msg = data;
    }
  }
}
</script>


<style scoped>

</style>

3、子页面代码:

<template>
  <h3>子页面</h3>
  <button @click="clickEventHandle">子页面按钮</button>
</template>

<script>
export default {
  // 父页面过来的方法,子组件要用emits来声明需要抛出的事件
  emits: ["myEvent"],
  methods: {
    clickEventHandle() {
      //自定义事件
      this.$emit('myEvent', '我是子页面内容');
      console.log('子页面点击了');
    }
  }
}
</script>

4、效果如下:

 

posted @ 2024-08-11 15:02  像一棵海草海草海草  阅读(179)  评论(0)    收藏  举报