30

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

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

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

4

3 回答 3

23

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

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

vm.$emit('test', 'hi')
// -> "hi"
于 2016-10-25T04:43:39.907 回答
12

在 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 的文档以获取有关此主题的更多信息。这是一个非常简短的介绍。

于 2017-10-19T15:03:59.163 回答
4

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

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

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

于 2019-04-23T00:15:39.930 回答