当前位置:网站首页>setup中的props和context

setup中的props和context

2022-07-23 00:47:00 只想挣钱,呜呜

props的使用:用于父子组件向子级组件传送数据

(1)在子级标签中写入要传送的数据

<child :msg="msg" mdf="123"></child>

(2)子级组件接收

props:['msg','mdf'],

(3)使用,直接使用即可

<h3>msg:{
    {
    msg}} {
    {
    mdf}}</h3>

如下图所示:
在这里插入图片描述

context的使用

context参数,是一个对象,里面有

(1) attrs对象:获取当前组件标签上的所有属性,与props的区别:
props在使用的时候,有个注册的过程,但是如果有的数据没有注册,依然可以通过context.attrs访问到

例如:

父组件:

<child :msg="msg" mdf="123"></child>

子组件:我只接受了一个msg,mdf没有接收

props:['msg'],

我怎么拿到mdf这个东西呢?这个时候可以通过context.attrs

setup(props,context) {
    
    console.log(context.attrs.mdf)
}

输出如下:
在这里插入图片描述
(2)emit方法:

emit是用来分发事件的,分发事件的目的是通过在子组件元素上绑定事件,来触发父组件中的事件,来改变父组件的数据

用法:

父组件:真正的改变数据的方法

//@xxx="xxx"---通过emit
<child :msg="msg" mdf="123" @xxx="xxx"></child>

const xxx = (txt:string) => {
    
  msg.value += txt
}
return {
    
  msg,
  xxx
}


子组件

<button @click="emitxxx">分发事件</button>

const emitxxx = () => {
    
  //xxx----父组件中的方法
  //'2123'---要给父组件传递的参数
  context.emit('xxx','2123')
}
return {
    
  emitxxx,
}

具体流程:
在这里插入图片描述

原网站

版权声明
本文为[只想挣钱,呜呜]所创,转载请带上原文链接,感谢
https://blog.csdn.net/m0_52518047/article/details/125819537