[英]Vue 3: How to pass data from component to App.vue when there is a router-view in between?
I have the following structure:我有以下结构:
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 中的“message”变量,但是当 Footer.vue 不是 App.vue 的直接子级(而是 Page.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 中没有消息出现:
//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 and ES6 modules ?也许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,
// ...
}
}
And now you import your composition in the components that need to access message
:现在您将您的作品导入需要访问
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>
If you want to quickly get started with Composition API, see this .如果您想快速开始使用 Composition API,请参阅此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.