我有一个相当简单的VueJS应用程序,3个组件(登录,SelectSomething,DoStuff)
登录组件只是用户和pass输入的表单,而第二个组件需要显示登录过程中获得的一些数据。
如何将数据从一个组件共享到其他组件?因此,当我路由到第二个组件时,我仍然拥有Login组件中获得的数据?
发布于 2016-10-25 12:43:40
您可以使用props或事件总线,在这两种总线中,您将能够从一个组件发出事件并侦听另一个组件
vm.$on('test', function (msg) {
console.log(msg)
})
vm.$emit('test', 'hi')
// -> "hi"
发布于 2017-10-19 23:03:59
在Vue.js中,组件可以使用props或events相互通信。这完全取决于组件之间的关系。
让我们举个小例子:
<template>
<h2>Parent Component</h2>
<child-component></child-component>
</template>
要将信息从父对象发送到子对象,您需要使用props:
<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的文档。这是一个非常简短的介绍。
发布于 2019-04-23 08:15:40
如果您有许多嵌套组件,请使用此小plugin:
Vue.use(VueGlobalVariable, {
globals: {
user: new User('user1'),
obj:{},
config:Config,
....
},
});
现在,您可以在任何组件中使用$user
,而无需使用props或其他
https://stackoverflow.com/questions/40224345
复制相似问题