Vue3 component parameter passing

Table of contents

1. Passing value from father to son

  • 1. emit
  • 2. props
  • 3.provide and inject

1. Passing value from father to son

1.emit

The code is as follows (example):

<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>

operation result:

insert image description here

The setup function of Vue3 provides two parameters propsand context

parameter value value
props immutable component parameters
context Attributes exposed by Vue3 (emit, slots, attrs)

2.props

The code is as follows (example):

<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>

operation result:

insert image description here

3.provide and inject

The code is as follows (example):

<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>

Summarize:

This article only briefly introduces the parameter transfer between components. If there are any deficiencies, please advise, and other content will continue to be added in the future.

Guess you like

Origin blog.csdn.net/Star_ZXT/article/details/123727762