vue父子组件间传递参数
1.父传子
使用 props 向子组件传递数据。
在父组件中定义 hMsg参数,v:bind 绑定childMsg的值为hMsg;
子组件使用props获取父组件传递过来的数据
parent.vue
<template>
<div>
<h2>parent</h2>
<Child1 :child1Msg="hMsg"></Child1>
</div>
</template>
<script>
import Child1 from './child1'
export default {
name: 'parent',
data () {
return {
hMsg: 'Child1MsgS'
}
},
components: {
Child1
}
}
</script>
child1.vue
使用props接收数据值
<template>
<div>{{child1Msg}}</div>
</template>
<script>
export default {
name: 'child1',
props: ['child1Msg']
}
</script>
2.子传父
子组件通过事件将数据传递给父组件
首先,子组件想要将username参数传递给父组件,用change事件来触发setUser函数,
在 setUser 中,使用了 $emit 来遍历 transferUser 事件,并返回 this.username
其中 transferUser 是一个自定义的事件,功能类似于一个中转,this.username 将通过这个事件传递给父组件
child2.vue
<template>
<div>
<label>用户名:</label>
<input v-model="username" @change="setUsername">
</div>
</template>
<script>
export default {
name: 'child2',
data () {
return {
username: ''
}
},
methods: {
setUsername: function () {
this.$emit('transferUser', this.username)
}
}
}
</script>
在父组件 中,声明了一个方法 getUser,用 transferUser 事件调用 getUser 方法,获取到从子组件传递过来的参数 username
getUser方法中的data,就是从子组件中传递过来的数据 username
parent.vue
<template>
<div>
<h2>parent</h2>
<Child2 @transferUser="getUser"></Child2>
<p>用户名为: {{user}}</p>
</div>
</template>
<script>
import Child2 from './child2'
export default {
name: 'parent',
data () {
return {
user: ''
}
},
components: {
Child2
},
methods: {
getUser: function (data) {
this.user = data
}
}
}
</script>