企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] ## 概述 组件引入必须是相对路径,加上 "./" ## 导入组件 vue3.0 可直接 通过import 导入 ``` import ChildComp from './ChildComp.vue' // 使用 <ChildComp /> ``` ## Props ``` <!-- ChildComp.vue --> <script setup> const props = defineProps({ msg: String }) </script> ``` 调用 ``` <ChildComp :msg="greeting" /> ``` ## 子组件触发事件给父组件 方式一: ``` <script setup> // 声明触发的事件 const emit = defineEmits(['response']) // 带参数触发 emit('response', 'hello from child') </script> ``` ``` <ChildComp @response="(msg) => childMsg = msg" /> ``` 方式二:()快捷 子,第二个值,为参数 ``` <h2 @click="$emit('world',msg)">gogogo</h2> ``` 父 ``` <MyComponent @world="useWorld" /> ``` ## 父组件传值给子子组件 provider,inject 父组件 ``` import { ref, provide } from 'vue' const count = ref(0) provide('key', count) ``` 子组件 ``` <script setup> import { inject } from 'vue' const message = inject('message') </script> ``` ## 子组件使用 v-model 默认 v-model 的 变量为 modelValue,也可更改 [教程](https://cn.vuejs.org/guide/components/events.html#usage-with-v-model) 子 ``` <script setup> defineProps(['modelValue']) defineEmits(['update:modelValue']) // 可省略 </script> <template> <input :value="modelValue" @input="$emit('update:modelValue', $event.target.value)" /> </template> ``` 父 ``` <CustomInput v-model="searchText" /> ``` ## 父组件调用子组件 在子组件中 ``` <script setup> import {ref} from "vue"; function childFn() { console.log('我是子组件'); } const msg = 'Hello World'; const num = ref(0); defineExpose({ // msg, num }); </script> ``` 父组件中 ``` <Index ref="I"></Index> <script setup> import Index from "./index.vue"; const I = ref(null); function test() { console.log(I.value.msg) // Hello World } </script> ``` ## props 检验 ``` defineProps({ // 基础类型检查 // (给出 `null` 和 `undefined` 值则会跳过任何类型检查) propA: Number, // 多种可能的类型 propB: [String, Number], // 必传,且为 String 类型 propC: { type: String, required: true }, // Number 类型的默认值 propD: { type: Number, default: 100 }, // 对象类型的默认值 propE: { type: Object, // 对象或数组的默认值 // 必须从一个工厂函数返回。 // 该函数接收组件所接收到的原始 prop 作为参数。 default(rawProps) { return { message: 'hello' } } }, // 自定义类型校验函数 propF: { validator(value) { // The value must match one of these strings return ['success', 'warning', 'danger'].includes(value) } }, // 函数类型的默认值 propG: { type: Function, // 不像对象或数组的默认,这不是一个工厂函数。这会是一个用来作为默认值的函数 default() { return 'Default function' } } }) ```