Vue 3: Как передать данные из компонента в App.vue, когда между ними есть маршрутизатор?

avatar
Martin Bernt Rud
1 июля 2021 в 20:12
1119
1
0

У меня есть следующая структура:

  • источник
    • компоненты
      • Footer.vue
    • просмотров
      • Page.vue
    • App.vue

Я хотел бы иметь доступ к переменной 'message' в App.vue, но я не могу понять, как это сделать, когда Footer.vue не является прямым дочерним элементом App.vue (но дочерним элементом Page .Vue, который через маршрутизатор является дочерним 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>
Источник

Ответы (1)

avatar
Cheetha
1 июля 2021 в 22:28
3

Возможно 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:

// 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, см. это.