父子组件传值

1.父传子

index.vue

<template>
  我是父组件
  <Child :str="str" />
</template>

<script setup>
  import Child from "./Child.vue";
  import { ref } from "vue";

  const str= ref("m");  // 传给子组件的值
</script>

Child.vue

<template>
  我是子组件 
  <div>从父组件传进来的值:{{ str}}</div>
</template>

<script setup>
  // 使用 defineProps 声明 props
  const props = defineProps({
    str: {
      type: String,
      default: "",
    },
  });
</script>

2.子传父

index.vue

<template>
  我是父组件
  <child @childChange="childChange" />
  <p>{{ str}}</p>
</template>

<script setup>
  import Child from "./Child.vue";
  import { ref } from "vue";

  const str= ref("");  // 从子组件传出的值
    // 组件的自定义事件
  const childChange = (val) => {
    str.value = val;
  };
</script>

Child.vue

<template>
  我是子组件 
 <el-button @click="handleClick">点我触发自定义事件</el-button>
</template>

<script setup>
     // 使用 defineEmits 声明 emits
  const emit = defineEmits(["childChange"]);
  const handleClick = () => {
    // 必须经过defineEmits声明,不然方法无效!
    emit("childChange", "我是经自定义方法传出的值");
  };
  });
</script>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容