美文网首页
父子组件传值

父子组件传值

作者: name_howe | 来源:发表于2024-11-21 15:51 被阅读0次

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>

相关文章

网友评论

      本文标题:父子组件传值

      本文链接:https://www.haomeiwen.com/subject/uvonvrtx.html