目录

Vue3 提供了多种组件参数传递方式,适用于不同场景的需求

Props 传递

事件传递($emit)

v-model 双向绑定

Provide/Inject 依赖注入

使用 Refs 访问子组件

使用 Pinia 或 Vuex 状态管理


Vue3 提供了多种组件参数传递方式,适用于不同场景的需求

Props 传递

Props 是父组件向子组件传递数据的主要方式。在 Vue3 中,Props 可以通过 defineProps 宏定义类型和默认值。

// 子组件
<script setup>
const props = defineProps({
  title: {
    type: String,
    required: true,
    default: '默认标题',
  },
  count: Number,
});
</script>

<template>
  <h1>{{ title }}</h1>
  <p>计数: {{ count }}</p>
</template>

// 父组件
<template>
  <ChildComponent title="Vue3 Props" :count="10" />
</template>

事件传递($emit)

子组件可以通过 $emit 向父组件发送事件并传递数据。Vue3 中推荐使用 defineEmits 宏显式声明事件。

// 子组件
<script setup>
const emit = defineEmits(['updateCount']);

const handleClick = () => {
  emit('updateCount', 5);
};
</script>

<template>
  <button @click="handleClick">增加计数</button>
</template>

// 父组件
<template>
  <ChildComponent @updateCount="handleUpdate" />
</template>

<script setup>
const handleUpdate = (value) => {
  console.log('更新的值:', value);
};
</script>

v-model 双向绑定

Vue3 支持通过 v-model 实现父子组件间的双向数据绑定,适用于表单输入等交互场景。

// 子组件
<script setup>
const props = defineProps(['modelValue']);
const emit = defineEmits(['update:modelValue']);

const handleInput = (e) => {
  emit('update:modelValue', e.target.value);
};
</script>

<template>
  <input :value="modelValue" @input="handleInput" />
</template>

// 父组件
<template>
  <ChildComponent v-model="inputValue" />
</template>

<script setup>
import { ref } from 'vue';
const inputValue = ref('');
</script>

Provide/Inject 依赖注入

对于跨层级组件通信,provideinject 可以避免逐层传递 Props 的繁琐。

// 祖先组件
<script setup>
import { provide } from 'vue';
provide('theme', 'dark');
</script>

// 后代组件
<script setup>
import { inject } from 'vue';
const theme = inject('theme', 'light'); // 默认值为 'light'
</script>

<template>
  <div :class="`theme-${theme}`">当前主题: {{ theme }}</div>
</template>

使用 Refs 访问子组件

父组件可以通过 ref 直接访问子组件的属性和方法。

// 子组件
<script setup>
const count = ref(0);
const increment = () => {
  count.value++;
};
defineExpose({ count, increment });
</script>

// 父组件
<template>
  <ChildComponent ref="childRef" />
  <button @click="childRef.increment()">调用子组件方法</button>
</template>

<script setup>
import { ref } from 'vue';
const childRef = ref(null);
</script>

使用 Pinia 或 Vuex 状态管理

对于全局状态共享,推荐使用 Pinia 或 Vuex 进行集中式管理。

// 使用 Pinia
import { defineStore } from 'pinia';

export const useCounterStore = defineStore('counter', {
  state: () => ({ count: 0 }),
  actions: {
    increment() {
      this.count++;
    },
  },
});

// 组件中使用
<script setup>
import { useCounterStore } from './store';
const counter = useCounterStore();
</script>

<template>
  <button @click="counter.increment()">{{ counter.count }}</button>
</template>

以上方法覆盖了 Vue3 中常用的组件参数传递方式,开发者可根据实际需求选择合适的方式。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐