vue3 组件学习

133 阅读2分钟

vue3 组件

  • Props

    • 使用 props 属性定义组件的输入属性,父组件可以通过这些属性向子组件传递数据。
    • 在子组件中,可以使用 setup() 函数的参数中的 props 对象访问这些属性。
  • Events

    • 可以使用 emits 选项定义组件的自定义事件,这允许子组件向父组件发送消息。
    • 在子组件中,可以使用 emit 方法触发自定义事件,并附带特定的参数。
  • Provide / Inject

    • 使用 provide 选项在父组件中提供数据,然后在子组件中使用 inject 选项来注入这些数据。
    • 这样可以在祖先组件和后代组件之间共享数据,而不需要通过 props 一层一层地传递。
  • v-model

    • v-model 是一个语法糖,用于实现组件的双向绑定。
    • 在组件内部,可以使用 modelValue 属性接收外部传入的值,并使用 ctx.emit('update:modelValue', newValue) 更新该值。
    • 在使用组件时,可以使用 v-model 指令来绑定组件的值,并自动同步更新。
  • 插槽(Slots)

    • 插槽是 Vue 组件中一种灵活的内容分发方式,允许将内容插入到组件中指定的位置。
    • 在组件模板中使用 <slot> 元素定义插槽的位置,父组件可以在插槽中插入任意内容。
  • 穿透属性(Attribute Inheritance)

    • Vue 3 中,子组件默认不会自动继承父组件的非 prop 属性(如 class 和 style)。
    • 使用 inheritAttrs: false 选项可以禁用属性的继承,而使用 $attrs 对象可以手动选择传递哪些属性给子组件。

下面是一个包含所有组件内容的示例:

## parent.vue

```vue
<template>
  <div>父级传入的v-model:{{ num }}</div>
  <child v-model="num">
    <template #preFix="{ message }">
      <span>preFix 插槽,{{ message }}</span>
    </template>
  </child>
</template>

<script setup>
import { ref, provide } from "vue";
import child from "./child.vue";
const num = ref(0);
provide("sharedData", "Shared data value");
</script>

<style></style>
## child.vue

```vue
<template>
  <div>
    <input :value="modelValue" @input="updateModelValue" />
    <slot name="preFix" message="hello"></slot>

    <button @click="updateModelValue(6)">更新v-model</button>
  </div>
</template>

<script>
import { defineComponent, inject } from "vue";

export default defineComponent({
  name: "ExampleComponent",
  props: {
    modelValue: {
      type: Number,
      required: true,
    },
  },
  emits: ["update:modelValue"],
  setup(props, context) {
    // 注入Inject
    const injectedData = inject("sharedData");
    console.log(injectedData, "injectedData");

    // 更新v-model
    const updateModelValue = (newValue) => {
      context.emit("update:modelValue", +newValue);
    };

    return {
      updateModelValue,
      injectedData,
    };
  },
});
</script>

在上述示例中,我们创建了一个名为 child 的组件,它展示了 Props、Provide/Inject、v-model、插槽和穿透属性等组件相关的知识点。

Ending

完结撒花❀