How can I share data between non parent-child components in Vue

后端 未结 3 1321
轮回少年
轮回少年 2020-12-03 08:09

I have 3 components (get-users, get-projects, get-tasks) - each contains a button which fires an ajax request to retreive some data. I want the data returned from the ajax r

相关标签:
3条回答
  • 2020-12-03 08:37

    Note: this answer is only valid for vue 1

    You could do a broadcast from the root Vue instance for example. this.$root gives you access to the root component in your current vue instance. Thus it will reach at its children:

    <script>
    export default {
        template: require('./get_users.template.html'),
    
        data: function() {
            return {
                userList: ''
            }
        },
    
        methods: {
            getUsers(e) {
                e.preventDefault();
    
                   this.$http.get('api/getusers').then(function (response) {
                        this.userList = response.data.users;
                        this.$root.broadcast('show-results:users', { users: response.data.users });
                })
            }
        }
    }
    </script>
    

    Then you listen for the show-results:users event in your show-results component:

    events: {
        'show-results:users': function(data) {
            // do your stuff here
        }
    }
    

    Of course you can give the event any name you want to.

    0 讨论(0)
  • 2020-12-03 08:38

    Use this small plugin if you want to share data between a lot of nested components:

    Vue.use(VueGlobalVariable, {
      globals: {
        user: new User('testuser'),
        ....
      },
    });
    

    use $user in any component!

    0 讨论(0)
  • 2020-12-03 08:56

    With Vue 2.0 things are bit different as broadcast has been deprecated. Vue documentation talks about using centralized event bus to accomplish this. Here's how you could it;

    1. Define centralized event hub. So in your The Vue instance/decalaration define

      const eventHub = new Vue() // Single event hub
      
      // Distribute to components using global mixin
      Vue.mixin({
          data: function () {
              return {
                  eventHub: eventHub
              }
          }
      })
      
    2. Now in your component you can emit events with

      this.eventHub.$emit('show-results:users', { users: response.data.users })
      
    3. And to listen you do

      this.eventHub.$on('show-results:users', data => {
      // do your thing
      })
      
    0 讨论(0)
提交回复
热议问题