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

导读:本篇文章讲解 vue3组件基础,组件引用与使用、向子组件传递数据与事件prop、emit,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

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

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/107042.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!