dan*_*els 26 vue.js vue-router vue-component vuejs2
我有一个相当简单的VueJS应用程序,3个组件(Login,SelectSomething,DoStuff)
登录组件只是用户和传递输入的表单,而第二个组件需要显示登录进度中获得的一些数据.
如何将数据从一个组件共享给其他组件?因此,当我路由到第二个组件时,我仍然在Login 1中获得了数据?
hig*_*rfs 19
您可以使用道具或事件总线,在那里您可以从组件中发出事件并侦听另一个事件
vm.$on('test', function (msg) {
console.log(msg)
})
vm.$emit('test', 'hi')
// -> "hi"
Run Code Online (Sandbox Code Playgroud)
小智 9
在Vue.js中,组件可以使用props或事件相互通信.这一切都取决于您的组件之间的关系.
我们来看一个小例子:
<template>
<h2>Parent Component</h2>
<child-component></child-component>
</template>
Run Code Online (Sandbox Code Playgroud)
要将信息从父级发送到Child,您需要使用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>
Run Code Online (Sandbox Code Playgroud)
要将孩子的信息发送给父母,您需要使用以下事件:
子组件
<script>
...
this.$emit('example', this.variable);
</script>
Run Code Online (Sandbox Code Playgroud)
父组件
<template>
<h2>Parent Component</h2>
<child-component @example="methodName"></child-component>
</template>
<script>
export default {
methods: {
methodName(variable){
...
}
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
有关此主题的更多信息,请查看vue.js的文档.这是一个非常简短的介绍.
如果您有很多嵌套组件,请使用此小插件:
Vue.use(VueGlobalVariable, {
globals: {
user: new User('user1'),
obj:{},
config:Config,
....
},
});
Run Code Online (Sandbox Code Playgroud)
现在,您可以$user在任何组件中使用,而无需使用道具或其他
| 归档时间: |
|
| 查看次数: |
21111 次 |
| 最近记录: |