1.父传子:
属性传递(Props):这是从父组件向子组件传递数据的最罕用形式。 在父组件的模板中,你能够应用子组件标签并增加属性来传递数据。 子组件通过 props 选项来接管这些数据。
父组件代码
<template> <div> 父组件 <Son :par="arr"></Son> </div> </template> <script setup lang="ts"> import Son from './son.vue' const arr='我是张三' </script> <style scoped > </style>
子组件代码
子组件承受数据
<template> <div> 子组件 </div></template><script setup lang="ts"> import {defineProps} from 'vue' const {par}=defineProps(['par']) console.log(par,'父组件传来的'); </script><style scoped ></style>
成果展现
2.子传父:
事件发射(defineEmits):子组件能够应用‘defineEmits定义一个自定义事件,并传递数据给父组件。父组件监听这个事件并解决数据。
子组件代码
<template> <div> <div @click="btn" class="box"> </div> </div> </template> <script setup lang="ts"> import {defineEmits} from 'vue' // 定义一个自定义事件 const emit=defineEmits(['up']) const value ='我是子组件' const btn=()=>{ //向父组件传值 emit('up',value) } </script> <style> .box{ width: 100px; height: 100px; border: solid 1px red; } </style>
父组件代码
<template> <div> 父组件 <Son1 @up="btns" ></Son1> </div> </template> <script setup lang="ts"> import Son1 from './son1.vue' const btns=(aa:string)=>{ console.log(aa,'子组件传来的值'); } </script> <style scoped > </style>
效果图
3.父间接获取子:
子组件通过defineExpose裸露给父组件
子组件
<template> <div> 子组件 </div></template><script setup lang="ts"> import { ref,defineExpose } from 'vue'; const arr=ref('你好') //通过defineExpose抛出 defineExpose({arr})</script><style></style>
父组件
<template> <div> 父组件 <Son3 ref="childRef"></Son3> <button @click="btn">点击</button> </div></template><script setup lang="ts"> import Son3 from './son3.vue' import { ref } from 'vue';const childRef=ref()const btn=()=>{ console.log(childRef.value.arr); }</script><style scoped ></style>
4.pinia应用
状态治理:Pinia 是 Vue 3 的状态治理库,它容许你在多个组件之间共享和治理状态。Pinia 提供了更简洁、更直观的形式来治理全局状态。
首先,装置 Pinia
npm i pinia
而后,在 Vue 中main.ts设置 Pinia
import { createApp } from 'vue' import { createPinia } from 'pinia' import App from './App.vue' import router from './router' const app = createApp(App) app.use(createPinia()) app.use(router) app.mount('#app')
接下来,你能够定义和应用 store:
import { defineStore } from 'pinia'export const useCounterStore = defineStore('main', { state: () => ({ count: 0, }), actions: { increment() { this.count++ }, randomizeCounter() { this.count = Math.round(100 * Math.random()) }, },})
在组件中应用
<template> <div> <button @click="store.randomizeCounter()">Randomize </button> {{ store.count }} </div></template><script setup lang="ts"> import { useCounterStore } from '../stores/counter'; const store = useCounterStore()// 将 action 作为 store 的办法进行调用store.randomizeCounter()</script><style scoped ></style>
成果