Vue父子组件传递笔记

发布于:2025-03-07 ⋅ 阅读:(24) ⋅ 点赞:(0)

Vue父子组件传递笔记

props 父组件向子组件进行传值

(1)在父组件APP.vue

<template>
  <div>
<!-- 给子组件Child.vue传递以msg的信号,传递的信息内容为messages -->
 <Child  :msg="messages"></Child>
  </div>
</template>
<script>
import { ref } from 'vue';
import Child from './components/Child.vue';

export default {
  components: {
    Child
  },
};
  data() {
    return {
<!-- 2、给要传递的值配值 -->
      messages : "这是父组件传到子组件的值"
    }
  },</script>

(2) 在子组件中:

<template>
    <div>
    <!-- 4、在子组件中调用msg -->
      <h2>子组件收获到父组件传来的值:{{ msg }}</h2>
    </div>
  </template>
  
  <script>
  export default {
    props: {
    <!-- 3、在子组件中写入props,然后声明传过来的msg的类型type和默认值default -->

        msg:{
            type:String,
            default:"默认值,没收到"
        }
    }, 
  };

emit 子组件向父组件传值(自定义 事件)

(1) 在子组件Child.vue中:

    <!--1、自定义一个事件 @click="xxxx" -->
    <!--2、在方法中发射"xxxx"事件的传递,this.$emit("信号名",传递值abc)-->

# 示例:

<template>
    <div>
      <button @click="send2father">点击,向父组件发射值</button>
    </div>
  </template>

  <script>
  export default {
    data() {
        return {
            child_data:"我是子组件的值",
        }
    },
methods:{

    send2father(){
        this.$emit("childmethod",this.child_data);
    }
}
  };
  </script>

(2)在父组件App.vue中:


<!--3、在父组件中,@信号名="获取到数据方法">
<!-- 4、在方法中 实现这个函数:获取到数据方法(传递值abc)-->

#示例:
<template>
  <div>
<!-- 子组件以emit发射childmethod这个信号,然后可以用repair方法来使用传回来的数据 -->
 <Child   @childmethod="repair"></Child>
  </div>
</template>

<script>
import Child  from './components/Child.vue';
export default {
  components: {
    Child
  },
methods: {
  repair(value){
    console.log(value + "接收到了");
   # 这里的value == 子组件传递的child_data
  }
}
</script>