vue3 setup语法糖及组件传递

309 阅读1分钟

setup的语法糖,可以将setup进行简化,不需要用components进行注册,同时也省略了return的返回值

 <template>
     <div>111</div>
 </template>
 <script setup>
 //这个书写代替原来export default setup的写法,更加方便
 </script>

1.1 组件引入

组件在props里直接引用就可以在template里直接使用,无需再进行注册

    <template>
        <div class="box">
            <!--子组件引用-->
            <v-child></v-child>
        </div>
    </template>
    <script setup>
        //引入后无需注册
        import v-child from '../components/child.vue'
    </script>

1.2 defineProps传参(父传子)

父元素传递给子元素的数据,子元素使用defineProps进行接收

//父元素
<template>
    <div class = "box">
    <!--子组件引用-->
    <v-child></v-child>
    </div>
</template>

//子元素
<template>
    <div class = "child">
        我是子组件
    </div>
</template>
<script setup>
    import {defineProps} from 'vue'
    //在接收的时候要注意,vue3 props接收必须规定数据类型,如果父元素数据类型出错,那么会报错
    const props = defineProps({msg:String})
    console.log(porps)
    console.log(props.msg)
</script>

1.3defineEmits传值(子传父)

//子组件
<tmeplate>
    <div class = "child">
        我是子组件
    </div>
</template>
<script setup>
    import {defineEmits,onMounted} from 'vue'
    const emit = defineEmits()
    onMounted(()=>{
    emit('getChildMsg','我是子元素')
    })
</script>

//父组件
<template>
    <div class = "box">
    <!--接收子元素的方法-->
    <v-child @getChildMsg="getmsg"></v-child>
    </div>
</template>
<script>
//引入不需注册
import v-child from '../components/child.vue'
let getmsg = e => {
    console.log(e)//我是子元素
}
</script>

1.4 defineExpose(父拿子方法)

在vue2中是使用this.refs,子组件名称.xxx方法,即可拿到子组件定义的值或者方法,在vue3中没办法这么拿去,必须子组件暴露后父组件才可以拿取到

<template>
    <div class = child>
        {{val}}
    </div>
</template>
<script setup>
import {ref,defineExpose} from 'vue'
let val = ref('我是子组件')
let fn = () => {
    val.value = '我改变了子组件'
}
//需要暴露才可以拿到方法
defineExpose({
    val,fn
})
</script>
//父组件
<template>
    <div class = "box">
        <!--接收子组件的方法-->
        <v-child ref = 'child'></v-child>
    </div>
</template>
<script setup>
//引入不需注册
import v-child from '../components/child.vue'
import {ref,onMounted} from 'vue'
//获取child实例
let child = ref()
onMounted(()=>{
    console.log(child.value.val)
    child.value.fn()
})
</script>