黑豹程序员-vue3 setup 子组件给父组件传值

工作原理

在子组件中调用emit方法触发父组件的方法实现传值

父组件 p.vue

bash 复制代码
<template>
  <div>
    <ChildComponent @childValue="handleChildValue"></ChildComponent>
    <button @click="getChildValue">获取子组件的值</button>
    {{receivedChildValue}}
  </div>
</template>

<script setup>
import { ref } from 'vue';
import ChildComponent from './child.vue';

const receivedChildValue = ref('');

const handleChildValue = (value) => {
  receivedChildValue.value = value;
};

const getChildValue = () => {
  console.log('Child Value:', receivedChildValue.value);
};
</script>

子组件:child.vue

bash 复制代码
<template>
  <div>
    <p>子组件的值: {{ childValue }}</p>
  </div>
</template>

<script setup>
import { ref, getCurrentInstance } from 'vue';

const childValue = ref('czs');
const instance = getCurrentInstance();

//子组件发生值给父组件,通过childValue事件触发
instance.emit('childValue', childValue.value);

</script>
相关推荐
JustHappy2 分钟前
「chrome extensions🛠️」我写了一个超级简单的浏览器插件Vue开发模板
前端·javascript·github
Loo国昌3 分钟前
Vue 3 前端工程化:架构、核心原理与生产实践
前端·vue.js·架构
sg_knight6 分钟前
拥抱未来:ECMAScript Modules (ESM) 深度解析
开发语言·前端·javascript·vue·ecmascript·web·esm
前端白袍27 分钟前
Vue:如何实现一个具有复制功能的文字按钮?
前端·javascript·vue.js
new code Boy1 小时前
escape谨慎使用
前端·javascript·vue.js
奶球不是球1 小时前
elementplus组件中el-calendar组件自定义日期单元格内容及样式
javascript·css·css3
傻啦嘿哟2 小时前
实战:用Splash搞定JavaScript密集型网页渲染
开发语言·javascript·ecmascript
冰敷逆向2 小时前
苏宁滑块VMP深入剖析(一):解混淆篇
javascript·爬虫·安全·web
小小鸟0083 小时前
JS(ES6+)基础
javascript·es6