vue3的新写法和特性整理——五、子组件向组件向父组件暴露方法

vue3中子组件向父组件暴露方法并传值,同样兼容老写法
1、父组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<template>
  <div class="home">
    <h1>父组件</h1>
    <img alt="Vue logo" src="../assets/logo.png" />
    <HelloWorld @changeMsg="changeMsg" :msg="msg" />
    <h1>{{num}}</h1>
  </div>
</template>
 
<script>
import { reactive, toRefs } from 'vue';
import HelloWorld from '@/components/HelloWorld';
export default {
  setup() {
    const state = reactive({
      msg: '点击修改父组件传值',
      num: 0
    });
    let changeMsg = x => {
      state.num += x;
    };
 
    return {
      ...toRefs(state),
      changeMsg
    };
  },
  name: 'Home',
  components: { HelloWorld }
};
</script>
 
<style scoped>
.home {
  color: red;
  border: 1px solid red;
   
}
</style>

  

2、子组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<template>
  <div class="hello">
    <h1>子组件</h1>
    <h1 class="pointer" @click="notifyParent">{{ msg }}</h1>
  </div>
</template>
 
<script>
import { toRefs } from 'vue';
export default {
  setup(props, context) {
    console.log(context);
 
    let notifyParent = () => {
      context.emit('change-msg', 2);
    };
    return {
      ...toRefs(props),
      notifyParent
    };
  },
  name: 'HelloWorld',
  props: {
    msg: String
  }
};
</script>
 
<style scoped>
.hello {
  margin: 20px;
  color: green;
  border: 1px solid green;
}
.pointer{
  cursor: pointer;
}
</style>

  

setup的第二个参数中包含了 attr emit slot
其中emit用于向父组件提交事件,需要注意的是vue3中的emit中的方法名不再支持驼峰写法,但父组件依旧支持驼峰和“-”间隔的写法,

emit其余用法和vue2相同
效果图

 

本文作者:我吃柠檬

本文链接:https://www.cnblogs.com/yjc-vue-react-java/p/13876720.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   我吃柠檬  阅读(3740)  评论(0编辑  收藏  举报
编辑推荐:
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
阅读排行:
· 《HelloGitHub》第 108 期
· Windows桌面应用自动更新解决方案SharpUpdater5发布
· 我的家庭实验室服务器集群硬件清单
· C# 13 中的新增功能实操
· Supergateway:MCP服务器的远程调试与集成工具
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起