父子组件:
// 父:
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>