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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值