父组件(传递数据):利用自定义属性传递数据。
- <template>
- <h3>我是父组件h3>
- <hr />
- <Child :name="info.name" :age="info.age">Child>
- template>
-
- <script setup>
- // 引入组件
- import Child from '../components/Child';
- // 引入 reactive 函数
- import { reactive } from 'vue';
- // 创建 reactive 数据
- let info = reactive({ name: "张三", age: 18 });
- script>
子组件(接收数据):使用 defineProps 接收数据。
- <template>
- <h3>我是子組件h3>
- <p>{{ name }} : {{ age }}p>
- template>
-
- <script setup>
- // 接收父组件传递的数据
- const props = defineProps(['name', 'age']);
- script>
注:defineProps 用于接收父组件传递的数据,不需要引入,可以直接使用。
父组件(接收数据):创建自定义事件,利用方法接收数据。
- <template>
- <h3>我是父组件h3>
- <hr />
- <Child @myEvent="add">Child>
- template>
-
- <script setup>
- // 引入组件
- import Child from '../components/Child';
- // 创建方法
- const add = (value) => {
- console.log('我是父组件', value);
- }
- script>
子组件(传递数据):使用 defineEmits 注册自定义事件传递数据。
- <template>
- <h3>我是子组件h3>
- <button @click="isShow">传递数据button>
- template>
-
- <script setup>
- // 注册父组件传递的自定义事件
- const emit = defineEmits(['myEvent']);
- // 创建方法调用自定义事件
- const isShow = () => {
- emit('myEvent', 666);
- }
- script>
注:defineEmits 用于注册自定义事件,不需要引入,可以直接使用。
- <template>
- <h3>我是父组件h3>
- <button @click="isShow = !isShow">切换组件button>
- <hr />
-
- <component :is="isShow ? A : B">component>
- template>
-
- <script setup>
- // 引入组件
- import A from '../components/A';
- import B from '../components/B';
- // 引入 ref 函数
- import { ref } from 'vue';
- // 创建 ref 数据
- const isShow = ref(true);
- script>
- <template>
- <h3 class="title">我是父组件h3>
- <button @click="state = 'blue'">按钮button>
- template>
-
- <script setup>
- // 引入 ref 函数
- import { ref } from "vue";
- // 创建 ref 数据
- let state = ref('red');
- script>
-
- <style scoped>
- .title {
- /* 使用 v-bind 绑定 CSS 样式 */
- color: v-bind('state');
- }
- style>
原创作者:吴小糖
创作时间:2023.10.19