vue3组件基础,组件引用与使用、向子组件传递数据与事件prop、emit

vue3组件基础,组件引用与使用、向子组件传递数据与事件prop、emit

一、组件模板

组成:template(必要),script,style
例子:模板名称 Hello.vue

<template>
    <div class="msgStyle">{
    
    {
    
     msg }}</div>
</template>

<script setup>
import {
    
     ref } from 'vue'
const msg = ref("组件模板")
</script>

<style>
.msgStyle {
    
    
    font-size: 30px;
}
</style>

二、引用与使用

父组件 使用 子组件,先用import引入,在直接引用

<script setup>
import Hello from './components/Hello.vue'
</script>

<template>
  <Hello/>
</template>

无setup语法糖使用

<script>
import Hello from './Hello.vue'
export default {
    
    
  components:{
    
    
    Hello:Hello
  },
}
</script>

三、向子组件传递数据

props

<template>
    <div class="msgStyle">{
    
    {
    
     msg }}</div>
</template>

<script setup>
defineProps({
    
    
  msg: String,
})
</script>

<style>
.msgStyle {
    
    
    font-size: 30px;
}
</style>

引用:直接添加msg,它会传递到子组件去,也:msg=msg,赋予动态数据

<template>
  <Hello msg="父向子传递数据"/>
</template>

注意:
数组或对象,需要添加一个返回值
无setup,则直接使用props

<script>
export default{
    
    
    props:{
    
    
        str:{
    
    
            str:String,//文本
            default:"组件默认值文本",
            required:true
        },
        arr:{
    
    //对象或数组的默认值必选从一个工厂函数返回
            type:Array,//对象是 object
            default(){
    
    
                return []
            }
        }
    }
}
</script>

四、子组件通过自定义事件向父组件传值 $emit

1 声明:父组件的函数,防止提示;如:parentMethod
2 在子组件中,通过$emit来触发事件

<template>
    <button @click="sendParent(msg)">提交数据给父组件:{
    
    {
    
    msg}}</button>
</template>

<script setup>
defineProps({
    
    
    msg: {
    
    
        type: String,
        default: "默认值"
    },
})

const emit = defineEmits(['parentMethod'])
function sendParent(e) {
    
    
    emit('parentMethod', e)
}
</script>

<style>
.msgStyle {
    
    
    font-size: 30px;
}
</style>

在父组件使用

<script setup>
import Hello from './components/Hello.vue'
function getChildMsg(e) {
    
    
  //打印内容
  console.log("子组件元素:" + e)
}
</script>

<template>
  <Hello msg="内容11" @parentMethod="getChildMsg"></Hello>
</template>

无setup写法,相同效果

<script>
export default {
    
    
    props:{
    
    
        msg: {
    
    
        type: String,
        default: "默认值"
    },
    },
    emits: ['parentMethod'],//无法自动继承,避免警告
    methods: {
    
    
        //在子组件中,通过$emit来触发事件
        sendParent(e) {
    
    
            //this.$emit('自定义事件的名称','发送的事件参数')
            this.$emit('parentMethod', e);
        }
    }
}
</script>

在这里插入图片描述
打印内容:

子组件元素:内容11

猜你喜欢

转载自blog.csdn.net/Linlietao0587/article/details/128359284
今日推荐