【问题标题】:How to share data between components in VueJS如何在 VueJS 中的组件之间共享数据
【发布时间】:2017-03-06 13:56:07
【问题描述】:

我有一个相当简单的 VueJS 应用程序,3 个组件(Login、SelectSomething、DoStuff)

登录组件只是一个表单,用于用户和传递输入,而第二个组件需要显示登录过程中获得的一些数据。

如何将数据从一个组件共享到其他组件?这样当我路由到第二个组件时,我仍然可以在登录组件中获得数据?

【问题讨论】:

  • 您是否阅读了state management 上的 Vue 指南中的部分?
  • 还没有,但它看起来像我需要的。猜猜这就是当您在完成阅读整个文档之前急于开始开发时会发生的情况。
  • 您好!如果您发现我的回答准确(并且有帮助),请accept it
  • @PatrickSteele 的答案是我一直在寻找的,但他将其添加为我无法“接受”的评论。有了您的回答,我只能将数据传递给子组件而不是兄弟组件。正确的?还是我错过了什么?

标签: vue-component vue-router vue.js vuejs2


【解决方案1】:

您可以使用props 或事件总线,您可以在其中从一个组件发出一个事件并在另一个组件上监听

vm.$on('test', function (msg) {
  console.log(msg)
})

vm.$emit('test', 'hi')
// -> "hi"

【讨论】:

    【解决方案2】:

    在 Vue.js 中,组件可以使用 propsevents 相互通信。这完全取决于您的组件之间的关系。

    我们来看这个小例子:

    <template>
    <h2>Parent Component</h2>
    <child-component></child-component>
    </template>
    

    要将信息从父级发送给子级,您需要使用道具:

    <template>
    <h2>Parent Component</h2>
    <child-component :propsName="example"></child-component>
    </template>
    
    <script>
    export default {
     data(){
      return{
       example: 'Send this variable to the child'
      }
     }
    }
    </script>
    

    要将信息从子级发送给父级,您需要使用事件:

    子组件

    <script>
     ...
     this.$emit('example', this.variable);
    </script>
    

    父组件

    <template>
    <h2>Parent Component</h2>
    <child-component @example="methodName"></child-component>
    </template>
    
    <script>
    export default {
     methods: {
      methodName(variable){
       ...
      }
     }
    }
    </script>
    

    查看 vue.js 的文档以获取有关此主题的更多信息。这是一个非常简短的介绍。

    【讨论】:

      【解决方案3】:

      如果您有很多嵌套组件,请使用这个小 plugin

      Vue.use(VueGlobalVariable, {
        globals: {
          user: new User('user1'),
          obj:{},
          config:Config,
          ....
        },
      });
      

      现在您可以在任何组件中使用$user,而无需使用道具或其他

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-31
        • 1970-01-01
        • 2017-08-16
        • 2021-11-11
        • 2020-08-31
        相关资源
        最近更新 更多