Vue3中常见传值方式
Props 方式
<template> <!-- 父组件--> <Bar :msg="'prop传值'"/> </template> <script setup> import Bar from './bar.vue' </script> ------------------------------------ <template> <!-- 子组件 --> <h1>{{ msg }}</h1> <button type="button" @click="count++"> fei 数量 {{ count }} </button> </template> <script setup> import { ref } from 'vue' defineProps({msg: String}) const count = ref(0) </script>
<template> <!-- 父组件--> <Bar @add="handleFei"/> </template> <script setup> import Bar from './bar.vue' const handleFei = (value) => { console.log("接受参数:", value); } </script> ------------------------------------ <template> <!-- 子组件 --> <button @click="feiClick">点击我触发emits</button> </template> <script setup> import { defineEmits } from 'vue' const emits = defineEmits(['add']) const feiClick = () => { emits("add","我是参数,传给父组件") } </script>
<template> <!-- 父组件--> <button @click="feiClick" >点击我触发emits</button> <Bar ref="feiRef"/> </template> <script setup> import Bar from './bar.vue' import {ref} from "vue"; const feiRef = ref(null); const feiClick = () => { // 调用子组件 feiRef.value.childrenFei(); } </script> ------------------------------------ <template> <!-- 子组件 --> </template> <script setup> const childrenFei = () => { console.log("接受父组件方法"); } // 暴露出去方法,让父组件调用 defineExpose({ childrenFei }) </script>
隔代传递
<template> <!-- 父组件--> <Bar /> </template> <script setup> import Bar from './bar.vue' import {provide} from "vue"; provide('list',"可以隔代传给子组件") </script> ------------------------------------ <template> <!-- 子组件 -->Provide/Inject <p>{{fei}}</p> </template> <script setup> import {inject} from "vue"; const fei = inject("list") </script>