• 注册
当前位置:1313e > vue >正文

Vue3中setup()函数收到的两个比较重要的值:props和context(和自定义事件有关)

Vue3中setup()函数收到的两个比较重要的值

setup()函数能接收到两个形参,一个是props,另外一个是context。props即父组件传递给子组件的参数,context意思是上下文,里面有一个emit('事件名', 事件回调函数收到的值)函数比较常用,可替代vue2绑定在vm身上的this.$emit('事件名', 事件回调函数收到的值);

子组件:

<template><h3>{{person.name}}h3><h3>{{person.age}}h3><button @click="sayHello">点我触发Person身上的hello事件button>
template><script>
import {reactive} from 'vue'
export default {name: 'Person',// 接收到的参数props:['name','age'],// 声明自定义事件emits:['hello'],setup(props,context){let person = reactive({name:props.name,age:props.age,})function sayHello(){// 触发自定义事件context.emit('hello','你好')}return {person,sayHello}}
}
script>

父组件:

<template><Person name="Ulrich" age="22" @hello="showHelloMsg">Person>
template><script>
import Person from "./components/Person.vue";
export default {name: "App",components: {Person,},setup() {function showHelloMsg(value) {console.log("hello事件被触发,收到的参数是: " + value);}return {showHelloMsg};},
};
script>

本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 162202241@qq.com 举报,一经查实,本站将立刻删除。

最新评论

欢迎您发表评论:

请登录之后再进行评论

登录