vue3组件之间常用的通信

开头

关于vue3组件之间常用的通信,做一个简单的归纳

1.父传子

用props去传递数据
父组件

<template>
  <div>
    <child title="测试标题"></child>
  </div>
</template>

<script setup>
import child from './child.vue';

</script>

子组件

<template>
  <div>
    <h1>标题:</h1>{{ title }}
  </div>
</template>

<script setup>
const props = defineProps(['title'])
</script>

2. 子传父

通过emits
父组件

<template>
  <div>
     子组件的count:{{ count }}
    <child @initEvent="initCount"></child>
  </div>
</template>
<script setup>
import child from "./child.vue";
import { ref } from "vue";
const count = ref();
function initCount(n) {
  count.value = n;
}
</script>

子组件

<template>
  <div>
    <el-button @click="$emit('initEvent', count)">获取这里的count值</el-button>
  </div>
</template>
<script setup>
import { ref } from "vue";
const emit = defineEmits(["initEvent"]);
const count = ref(1);
</script>

3.ref + defineExpose

子组件中用defineExpose暴露出相关内容,父组件用ref去调用相关内容
父组件

<template>
  <div>
    <child ref="childRef"></child>
    <el-button @click="viewChild">查看子组件暴露的内容</el-button>
  </div>
</template>
<script setup>
import child from "./child.vue";
import { ref } from "vue";
const childRef = ref();
const viewChild=()=>{
    console.log('childRef',childRef.value);
}
</script>

子组件

<script setup>
import { ref } from "vue";
const title = ref("我是子组件");
const calback= ()=>{
  console.log('这里是子组件')
}
defineExpose({
    title,
    calback
})
</script>

在这里插入图片描述

4.vuex/pinia

pinia.js

import { defineStore } from "pinia";
export const demoStore = defineStore("demoStore ", {
  state: () => ({
   name:'demoStore ',
  }),
  actions: {
  	demo(){
		console.log("111");
	}
  },
});

index.vue 用法是个人习惯

import { toRefs} from "vue";
// //pinia状态管理
import { demoStore } from "./store";
// 使用解构赋值
const store = demoStore ();
const {
  name
} = toRefs(store); //变量
const {
  demo
} = store; //方法

5.provide/inject

外层组件

<template>
  <div>
    <child/>
  </div>
</template>

<script setup>
import child from "./child.vue";
import { ref, provide } from "vue";
provide("name", 111);
</script>

后代组件

<template>
    <div>{{ name }}</div>
</template>
<script setup>
import { inject } from 'vue'
// 接收顶层组件的通信
const name = inject('name')
</script>

6.路由传参

query传参,params和这个类似
发送

router.push({
   name: 'child', 
   query: {
       demo: '测试'
   }

接收

import { useRoute} from 'vue-router'
const route = useRoute()
console.log(route.query.demo) 

7.浏览器缓存

// 存
localStorage.setItem('key', 'value');
sessionStorage.setItem('key', 'value');
// 获取
const valueFromLocalStorage = localStorage.getItem('key');
const valueFromSessionStorage = sessionStorage.getItem('key');
// 删除
localStorage.removeItem('key');
sessionStorage.removeItem('key');
// 清空所有
localStorage.clear();
sessionStorage.clear();

结尾

自己常用的一些通信方式,如果有不足麻烦关照提醒一下

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值