vue3的组件的编写及父子组件传递数据

Javascript piniu 597浏览 0评论

一、组件的分类

我们会把组件分成两个类型,一个是共用型的组件,一个是普通型单页组件

二、创建一个vue3的组件

1. 使用defineProps方法暴露要传递的属性(父组件向子组件传递数据)

以一个按钮组件(子组件)为例:

//MyButton.vue
<template>
  <div class="button-box">
    <button class="button-content" :style="bgColor">
      {{ buttonName }}
    </button>
  </div>
</template>

<script setup>
import { defineProps, computed } from "vue";
let props = defineProps({
  buttonName: {
    type: String,
    default: "按钮",
    required: true
  },
  bgColorType: {
    type: String,
    default: "white"
  }
});
const bgObj = {
  black: "#00",
  white: "#fff",
  red: "#f5222d",
  orange: "#fa541c",
  yellow: "#fadb14",
  green: "#73d13d",
  blue: "#40a9ff"
};
const bgColor = computed(() => {
  return `background-color:${bgObj[props.bgColorType]};`;
});

</script>
<style>
.button-content {
  border: 1px solid lightskyblue;
}
</style>

在vue页面(父组件)中使用:

<template>
  <div class="box"></div>
  <MyButton buttonName="桃花依旧笑春风"></MyButton>
</template>

<script setup>
   import MyButton from "../components/MyButton.vue";
</script>

<style>
</style>

也就是vue2中的props变成了defineProps来创建。创建后,其内的属性可以直接使用。

2.组件的事件绑定 (子组件向父组件传递数据)

在vue2中使用emit来抛出事件。而在vue3中,我们需要先利用defineEmits先注册要抛出的事件数组,返回一个emit对象。然后利用它来抛出事件

在按钮组件(子组件)中:

<template>
   <button
      class="button-content"
      :style="bgColor"
      @click="buttonClick(buttonName)"
      @mouseover="mouseHover"
    >
      {{ buttonName }}
    </button>
</template>

<script setup>
    import { defineProps, defineEmits, computed, ref } from "vue";
   
    let emits = defineEmits(["buttonClick", "mouseHover"]); //注册要抛出的事件数组,返回emits
    
    function buttonClick(val) {
      //点击触发这个事件,于是调用emit,来抛出事件
      let name = val === "桃花依旧笑春风" ? "人面不知何去处" : "桃花依旧笑春风";
      emits("buttonClick", name);
    }

    function mouseHover() {
      emits("mouseHover");
    }
   
</script>

在父组件的使用:

<template>
  <div class="box"></div>
  <MyButton
    :buttonName="buttonContent"
    :bgColorType="bgtype"
    @buttonClick="myButtonClick"
    @mouseHover="myBtnHover"
  ></MyButton>
</template>

<script setup>
import MyButton from "../components/MyButton.vue";
import { ref } from "vue";
let bgtype = ref("white");
let buttonContent = ref("桃花依旧笑春风");

function myButtonClick(val) {
  buttonContent.value = val;
}

function myBtnHover() {
  bgtype.value = "orange";
  setTimeout(() => {
    bgtype.value = "white";
  }, 1000);
}

</script>


发表我的评论
取消评论
表情

Hi,您需要填写昵称和邮箱!

  • * 昵称:
  • * 邮箱: