Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

javascript - Vuejs Share Data Between Components

I have two components:

  • App.vue
  • Sidekick.vue

In my App.vue component, I have a property that I would like to access from Sidekick.vue

App.vue

<template>
  <div id="app">
    <p>{{ myData }}</p>
    <div class="sidebar">
      <router-view/> // our sidekick component is shown here
    </div>
  </div>
</template>

<script>
export default {
  name: 'App',
  data () {
    return {
      myData: 'is just this string'
    }
  }
}
</script>

Sidekick.vue

<template>
  <div class="sidekick">
    {{ myData }}
  </div>
</template>

<script>
export default {
  name: 'Sidekick'
}
</script>

I would like access to myData (which is declared in App.vue) from Sidekick.vue

I have tried importing App.vue from within Sidekick.vue by doing something like:

Sidekick.vue (incorrect attempt)

<script>
import App from '@/App'
export default {
  name: 'Sidekick',
  data () {
    return {
      myData: App.myData
    }
  }
}
</script>

I have read about props - but have only seen references to child / parent components. In my case, Sidekick.vue is shown in a div inside App.vue (not sure if this makes it a "child"). Do I need to give access of myData to <router-view/> somehow?

UPDATE: (to show relationship between App.vue and Sidekick.vue

index.js (router file)

import Vue from 'vue'
import Router from 'vue-router'
import Sidekick from '@/components/Sidekick',
import FakeComponent from '@/components/FakeComponent'

Vue.use(Router)

const router = new Router({
  routes: [
    {
      path: '/',
      redirect: '/fakecomponent'
    },
    {
      path: '/sidekick',
      name: 'Sidekick',
      component: Sidekick
    },
    {
      path: '/fakecomponent',
      name: 'FakeComponent',
      component: FakeComponent
    }
  ]
})

export default router

Sidekick.vue gets rendered when we hit /sidekick

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just keep in mind, the rule of thumb is using props to pass data in a one-way flow

props down, events up.
https://vuejs.org/v2/guide/components.html#Composing-Components

Quick solution:

Global event bus to post messages between your <App/> and <Sidekick/> components.

https://vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication

Long term solution:

Use a state management library like vuex to better encapsulates data in one place (a global store) and subscribe it from your components tree using import { mapState, mapMutations } from 'vuex'


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...