前言

没啥好说的,淦就完事了,按照自己的认知简单的整理了一下vue3的组件传参……

一、父子传值

1.emit

代码如下 (示例):

<template>
  <div>
    子组件: <button @click="childEmit">传值给父组件</button>
  </div>
</template>
<script>
export default {
    setup(props,{emit}){ //分解context对象取出emit
        function childEmit(){
            emit('my-emit','我是子组件值')
        }
        return{
            childEmit
        }
    }
};
</script>
<template>
  <div>
    父组件 <child @my-emit="parentEmit"></child>
  </div>
</template>

<script>
import Child from "./Child.vue";
import { ref } from "vue";
export default {
  components: {
    Child,
  },
  setup() {
    function parentEmit(val){
        alert(val)
    }
    return{
        parentEmit
    }
  },
};
</script>

看一下运行结果:

在这里插入图片描述

还记得上一篇文章中说过Vue3取消了this上下文,this.$emit咋整嘞?
Vue3的setup函数提供了两个参数 propscontext

参数Value
props不可变的组件参数
contextVue3暴露出来的属性(emit,slots,attrs)

所以访问就变成了这种形式:

this.xxx ====》context.xxx

2.props

代码如下 (示例):

<template>
    <div>
        <div>{{msg}}</div>
        <div>{{str}}</div>
    </div>
</template>
<script>
import {computed} from 'vue'
export default {
    props:{
        msg:String
    },
    setup(props){//提供的函数props直接用就完事了嗷~~~
        const str = computed(()=>{
            return '父组件值为:'+ props.msg
        })
        return{
            str
        }
    }
}
</script>
<template>
    <child :msg="msg"></child>
</template>
<script>
import Child from './Child.vue'
import {ref} from 'vue'
export default {
    components:{
        Child
    },
    setup(){
        const msg = ref('I am father value!')
        return{
            msg
        }
    }
}
</script>

看一下运行结果:

在这里插入图片描述

3.provide和inject

代码如下 (示例):

<template>
    <child ref="HelloWorld"></child>
</template>
<script>
import Child from './Child.vue'
import {reactive,provide} from 'vue'
export default {
    components:{
        Child
    },
    setup(){
        const state = reactive({msg:'1234'})
        provide('proMsg',state)
        return{
            state
        }
    }
}
</script>
<template>
    <div>
        <h1>{{ofMsg.msg}}</h1>
    </div>
</template>
<script>
import {inject,ref} from 'vue'
export default {
    setup(){
        const ofMsg = inject('proMsg',ref('none'))
        return{
            ofMsg
        }
    }
}
</script>

看一下运行结果:
在这里插入图片描述
provide,inject用法和之前Vue2用法没什么区别,哦豁一把嗦~~~


总结

以上就是今天要讲的内容,本文仅仅简单介绍了组件之间的传参,后续其他内容会继续补充。

Logo

前往低代码交流专区

更多推荐