父组件向子组件传值
简短说来就是,父组件通过标签动态绑定来传递数据,子组件通过props,以数组的形势来接收。
首先写一个子组件header.vue。
html部分:

如果要从父组件接收数据,那么就要使用props。这个logo是在父组件中定义的。
js部分:

父组件部分:在父组件中注册子组件。 logo就是子组件中接收的名字。后面是要传送的数据。


子组件向父组件传值
子组件主要通过事件传递数据给父组件。
子组件部分:要将input输入的用户名传到父组件中去。首先声明一个了方法 setUser,用 change 事件来调用 setUser。在setUser方法中通过this.$eimt来遍历 transferUser 事件,并返回 this.username。
其中 transferUser 是一个自定义的事件,功能类似于一个中转,this.username 将通过这个事件传递给父组件


父组件部分
在父组件 App.vue 中,声明了一个方法 getUser,里面的msg就是子组件传送过来的username,用 transferUser 事件调用 getUser 方法,获取到从子组件传递过来的参数 username。



网友评论