Vue3父子组件传值(个人笔记)
2022-08-24 本文已影响0人
kevision
本文基于
<script setup>
方式
defineProps和defineEmits实现父子组件传值
子组件
<template>
<div>
<!-- 方式一 直接调用$emit-->
<el-button @click="$emit('sonClick', '子组件数据')">子按钮{{msg}}</el-button>
<!-- 方式二 -->
<el-button @click="handleGetMsg">子按钮{{msg}}</el-button>
</div>
</template>
<script setup>
import { ref } from 'vue'
// defineProps声明props,返回一个对象,其中包含了传递给子组件的所有 props
defineProps({
msg: {
type: String,
default: ''
}
})
// setup中不能使用$emit
// 通过 defineEmits 宏来声明需要抛出的事件,返回一个等同于$emit的函数
const emit = defineEmits(['sonClick'])
function handleGetMsg() {
emit("sonClick", "子组件向父组件传送的信息");
}
</script>
父组件
<template>
<div>
<div>son:{{ myname }}</div>
<son :msg="msg" @sonClick="sonClick"></son>
</div>
</template>
<script setup>
import { ref } from 'vue'
import son from '@/components/son.vue' // 通过 <script setup>导入的组件都在模板中直接可用
const msg = ref('父组件信息')
const myname = ref('')
function sonClick(val) {
myname.value = val
}
</script>
ref操作符实现父子组件传值
子组件
<template>
<div>
<el-button >子按钮</el-button>
</div>
</template>
<script setup>
import { ref } from 'vue'
const a = ref('a')
function sonEvent() {
console.log("sonEvent")
}
// setup里面是默认私有的,父组件无法访问,需要通过defineExpose暴露出去,父组件才能访问
defineExpose({
sonEvent,
a
})
</script>
父组件
<template>
<div>
<son ref="myson"></son>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import son from '@/components/son.vue' // 不用注册
// ref操作dom, myson必须和模板里ref的值一致
const myson = ref(null)
onMounted(() => {
myson.value.sonEvent()
console.log('a', myson.value.a)
})
</script>
provide和inject依赖注入实现父子组件传值
父组件
<script setup>
import { ref, provide } from 'vue'
const count = ref(0)
function add() {
count.value++
}
provide('obj', {
count,
add
})
</script>
子组件
<template>
<div>
<div>count: {{count}}</div>
<el-button @click="add">加一</el-button>
</div>
</template>
<script setup>
import { inject } from 'vue'
const { count, add } = inject('obj')
</script>
slot作用域插槽实现父子组件传值
子组件
<!-- <MyComponent> 的模板 -->
<div>
<slot :text="greetingMessage" :count="1"></slot>
</div>
父组件
当父组件需要接收插槽 props 时,通过子组件标签上的 v-slot
指令,直接接收到了一个插槽 props 对象:
<MyComponent v-slot="slotProps">
{{ slotProps.text }} {{ slotProps.count }}
</MyComponent>
props解构:
<MyComponent v-slot="{ text, count }">
{{ text }} {{ count }}
</MyComponent>
reactive小型store实现组件间传值
// utils/store.js
import { reactive } from "vue";
export const store = reactive({
count: 0,
increment() {
this.count++
}
})
组件1
<template>
<div>
<el-button @click="store.increment()">加1</el-button>
</div>
</template>
<script setup>
import { ref } from 'vue'
import { store } from '../utils/store.js'
</script>
组件2
<template>
<div>
<div>count: {{store.count}}</div>
</div>
</template>
<script setup>
// setup里面引入的变量、方法等都可以在模板中直接访问 (vue2引入外部的方法在模板中使用需要在methods中暴露)
import { store } from '../utils/store.js'
</script>
未完待续......