vue3的state方式传递参数
在Vue 3中,可以使用setup()函数和reactive或ref来创建和管理状态(state)。如果你想在组件之间传递参数,可以使用props和emit。
下面是一个简单的示例,演示如何在Vue 3中通过状态传递参数:
1.
创建一个父组件(ParentComponent):
2.
vue复制代码
<template> | |
<div> | |
<input v-model="message" type="text" placeholder="Enter message"> | |
<button @click="sendMessage">Send</button> | |
<ChildComponent :message="message" @received="handleReceived"/> | |
</div> | |
</template> | |
<script> | |
import { ref } from 'vue'; | |
import ChildComponent from './ChildComponent.vue'; | |
export default { | |
components: { | |
ChildComponent | |
}, | |
setup() { | |
const message = ref(''); | |
const sendMessage = () => { | |
message.value = 'Hello from ParentComponent!'; | |
}; | |
const handleReceived = (receivedMessage) => { | |
console.log('Received from ChildComponent:', receivedMessage); | |
}; | |
return { message, sendMessage, handleReceived }; | |
} | |
}; | |
</script> | |
1.
创建一个子组件(ChildComponent):
2.
vue复制代码
<template> | |
<div> | |
<p>{{ message }}</p> | |
<button @click="sendBack">Send Back</button> | |
</div> | |
</template> | |
<script> | |
export default { | |
props: ['message'], | |
setup() { | |
const sendBack = () => { | |
const receivedMessage = 'Hello from ChildComponent!'; | |
console.log('Sending back to ParentComponent:', receivedMessage); | |
// 传递参数回父组件 | |
this.$emit('received', receivedMessage); | |
}; | |
return { sendBack }; | |
} | |
}; | |
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论