Vue3知识结构之组件
组件:代表局部功能代码和资源的集合
一、插槽 Slots
1.默认插槽
<slot></slot>
//默认插槽 放在复用的组件对应位置
2.具名插槽
<slot name='footer'></slot>
当子组件需要显示不同的效果时使用具名插槽,通过name属性给插槽命名。
3.作用域插槽
在封装组件的过程中,可以为预留的插槽绑定 props 数据,这种带有 props 数据的叫做作用域插槽。通过作用域插槽,把组件数据返回给,组件调用方。
<slot :info="infomation" :msg="message"></slot>
二、动态组件
<component :is="componentAlbum"></component>
代码示例:
<template>
<div class="title">动态组件</div>
<div class="inner">
<component :is="componentAlbum"></component>
<button @click="changeComponent">组件间通信切换</button>
</div>
</template>
<script setup>
import TextAlbumVue from '@/';
import PhotoAlbumVue from '@/';
import { shallowRef } from 'vue';
let componentAlbum = shallowRef(TextAlbumVue)
function changeComponent() {
if (componentAlbum.value.__file === PhotoAlbumVue.__file) {
componentAlbum.value = TextAlbumVue;
} else {
componentAlbum.value = PhotoAlbumVue;
}
}
shallowRef和ref响应式变量用法相同
是ref的深监听 ,相比ref需要硬件资源开销大
监听组件的时候使用shallowRef
三、组件间传值
1.父子间传值
父传子 defineProps
子组件 defineProps函数定义接收的值
const jsonProps=defineProps({
content:String,
objinfo:Object,
})
父组件 自定义属性传出
<Child :content="content" :objinfo="objinfo"></Child>
子传父 defineEmits
子组件 定义一个事件和要传的值,然后抛出(emit)
const emitsFunc=defineEmits(['toFather','toFatherobj'])
function toFatherClick(){
emitsFunc('toFather',inputValue.value);
}
父组件 引用该子组件时调用 自定义事件
<sendChild @toFather="recriveFromSon"></sendChild>
//script
function recriveFromSon(va){
content.value=va;
}
2.父组件调用子组件的函数
defineExpose
子组件 子组件暴露成员
function handleShow(va,vb){
alert('函数handleShow被调用');
console.log(va,vb);
}
defineExpose({
content, //值
handleShow,//函数方法
})
父组件 ref调用
<Child ref="commChildValue"></Child>// ref 获取子组件
//script
let a=ref(0),b=ref(0),spanInfo=ref('');
const commChildValue=ref(null); //定义变量
onMounted(()=>{
spanInfo=commChildValue.value.content;//传递的值在挂载完毕后
})
function invokeChild(){
commChildValue.value.handleShow(a.value,b.value)//通过函数形参变相完成父传子
}
ref 也可以进行操作dom
<span ref="refDomstr"></span>
//script
let spanInner=ref('');
onMounted(()=>{
refDomstr.value.innerText='ref操作Dom';
refDomstr.value.style.color='blue';
})
3.pinia 状态管理
多个组件需要使用同一个变量;
兄弟组件需要使用同一个变量;
爷孙组件需要使用同一个变量时,可以使用pinia做数据存储
使用前 需要进行下载
npm install pinia
在src文件路径下,新建store文件夹,并新建js文件
import { defineStore } from "pinia";
//option store
export const useUserStore = defineStore('user', {
state: () => {
return {
name: '',
count: 0
}
},
getters: {
doubleCount(state) {
return state.count * 2;
}
},
actions: {
getCount() {
this.count++;
}
}
})
pinia的语法中的
state => 选项式API中的 data,用来定义变量;
getters => computed,用来属性计算;
actions =>选项式API中的 methos,用来定义函数
同样,pinia也有组合式语法的写法
//setup store
import { ref, computed } from 'vue';
export const useUserStore = defineStore('user',()=>{
const name = ref('');
const count = ref(0);
const doubleCount = computed((count) => { return count.value * 2 });
function getCount() {
count.value++;
}
return { name, count, doubleCount, getCount }
})