vue3兄弟组件传值方式mitt.js
vue3中兄弟组件传值的方式mitt下载mittyarn add mitt或者npm install mitt方式一: 在main.js中注册挂载到全局import { createApp } from 'vue'import { createPinia } from 'pinia'import App from './App.vue'// 导入mittimport mitt from 'mitt
·
vue3中兄弟组件传值的方式mitt
下载mitt
yarn add mitt
或者
npm install mitt
方式一: 在main.js中注册挂载到全局
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
// 导入mitt
import mitt from 'mitt'
const app = createApp(App)
// vue3挂载到全局
app.config.globalProperties.$mitt = new mitt();
app.use(createPinia()).mount('#app')
2.在组建中使用
组件1 发送数据
<template>
<h2>组件1: {{money}}</h2>
<button @click="sendMitt">$mitt发送数据</button>
</template>
<script>
import { getCurrentInstance, ref } from 'vue'
export default {
setup() {
let { proxy } = getCurrentInstance()
let money = ref(100)
function sendMitt() {
proxy.$mitt.emit('mittFn', money.value-=2)
}
return {
money,
sendMitt,
}
}
}
</script>
组件2 接收数据
<template>
<h2>组件2接收mitt发送的数据: {{money}}</h2>
</template>
<script>
import { getCurrentInstance, ref } from 'vue'
export default {
setup() {
let { proxy } = getCurrentInstance()
let money = ref('')
proxy.$mitt.on('mittFn', (res) => {
console.log(res)
money.value = res
})
return {
money,
}
}
}
</script>
方式二: 创建mitt.js文件
import mitt from 'mitt'
export default new mitt()
组件1 发送数据
<template>
<h2>组件1: {{money}}</h2>
<button @click="sendMitt">$mitt发送数据</button>
</template>
<script>
import { ref } from 'vue'
import mitt from '../mitt/index.js'
export default {
setup() {
let money = ref(100)
function sendMitt() {
mitt.emit('mittFn', money.value-=2)
}
return {
money,
sendMitt,
}
}
}
</script>
组件2 接收数据
<template>
<h2>组件2接收mitt发送的数据: {{money}}</h2>
</template>
<script>
import { ref } from 'vue'
import mitt from '../mitt/index.js'
export default {
setup() {
let money = ref('')
mitt.on('mittFn', (res) => {
console.log(res)
money.value = res
})
return {
money,
}
}
}
</script>
更多推荐
已为社区贡献4条内容
所有评论(0)