Vue 3:当中间有路由器视图时,如何将数据从组件传递到 App.vue? [英] Vue 3: How to pass data from component to App.vue when there is a router-view in between?
问题描述
我有以下结构:
- 源代码
- 组件
- Footer.vue
- Page.vue
我希望能够访问 App.vue 中的 'message' 变量,但是当 Footer.vue 不是 App.vue 的直接子级(而是 Page 的子级)时,我不知道该怎么做.Vue - 通过路由器 - 是子 App.vue).
I would like to be able to access the 'message' variable in App.vue, but I can´t figure out how to do it when Footer.vue is not a direct child of App.vue (but child of Page.Vue which - via the router - is child App.vue).
我需要在我的文件中添加什么?现在有如下 - 并且(当然)App.vue 中没有消息出现:
What do I need to add in my files? There are now as follows - and (of course) no message appears in App.vue:
//App.vue <template> <p>Message is: {{ message }}</p> <router-view /> </template> <style lang="scss"> @import "./_scss/main.scss"; </style>
.
//Page.vue <template> <Footer/> </template> <script> import Footer from '@/components/Footer.vue' export default { components: { Footer } } </script>
.
//Footer.vue <template> <input v-model="message" placeholder="edit me"> <p>Message is: {{ message }}</p> </template> <script> export default { data() { return { message: '' } } } </script>
推荐答案
Maybe Composition API 和 ES6 模块?
@/compositions/composition.js import { ref } from 'vue' const message = ref('test'); export const useComposition = function() { // other functions, for example to mutate message ref return { message, // ... } }
现在你在需要访问
message
的组件中导入你的作品:And now you import your composition in the components that need to access
message
:// Footer.vue, App.vue <script> import { defineComponent } from 'vue' import { useComposition } from '@/compositions/composition' export default defineComponent({ setup() { const { message } = useComposition(); return { // make it available in <template> message } }, }) </script>
如果您想快速开始使用 Composition API,请看这里.
If you want to quickly get started with Composition API, see this.
这篇关于Vue 3:当中间有路由器视图时,如何将数据从组件传递到 App.vue?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- 组件