专业的编程技术博客社区

网站首页 > 博客文章 正文

vue3+ts 组件通信(emit、pinia和mitt的使用)

baijin 2025-01-04 16:56:57 博客文章 16 ℃ 0 评论

父子组件:


// 父:
const childList=[{ // 数据
  name:"child1",
  children:[{
	  text:"hello"
  }]
  },{
  name:"child2",
  children:[{
 	 text:"world"
  }]
}]
// 子的close的方法
const closeChildFn = (val) => {
	console.log(val)
}
<Child :data='childList' :title="'我是父'" @close='closeChildFn'></Child>


// 子
const props = defineProps({// 接收数据
  title: String,
  data: Object
})
const emit = defineEmits(['close']);// emit方法名
const closeMySelfFn = () => {
	emit('close',props.data)// 传给父
}
<button @click='closeMySelfFn'>关闭我自己</button>

跨组件:

// 创建store xxStore.ts
import {defineStore} from 'pinia';
import {store} from '@/store'
import {emitter} from '@/utils/mitt'
// 数据
export const xxStore = defineStore({
  id:'xx',
  state:()=>({
 	 str:'haha',
    list:[{
    	id:111,
    	name:"hello",
   	 text:"enheng"
    },{
      id:22,
      name:"world",
      text:"huhu"
    }]
  }),
  actions:{
    changeStr(newVal){
      this.str = newVal
    }
  },
	getters:{
    getStr(state){
      return state.str
    }
  }
})
// 方法
emitter.on('changFn',str);
export default function xxStoreHook(){
	return xxStore(store)
}
// 使用
import {emitter} from '@/utils/mitt'
import xxStoreHook from '@/store/xxStore.ts'
const xxStore = xxStoreHook();// 引入store
// 方法
const changeFn = () => {
	emitter.emit('changeFn','hello,world')
}
console.log(xxStore().getStr) // 获取store里getters里的
console.log(xxStore.str) // 获取store里state里的值
xxStore.changeStr('啦啦啦') // store里的actions

<div>store中str的值为:{{xxStore.str}}</div>
<button @click='changeFn'>点击改变str的值</button>

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表