父组件向子组件传值

父组件向子组件传值的方式通常是通过子组件定义的props来完成的。子组件定义props作为传入的数据,父组件应用子组件时绑定props,就能够动态地改变props的值,实现实时传值。

Son.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
<template>
<div>
<span>{{msg}}</span>
</div>
</template>
<script>
export default {
name: 'Son',
props: {
msg: String //定义了props及其类型
}
}
</script>

Father.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<template>
<div>
<Son :msg="myMsg"></Son>
<input type="text" v-model="myMsg">
</div>
</template>
<script>
import Son from './Son.vue'
export default {
components: {
Son
},
data () {
return {
myMsg: 'Welcome to Your Vue.js App'
}
}
}
</script>

Son组件定义了props(msg)且类型为String,Father组件引用了Son组件,并传入Mymsg作为props值。Father组件还用Input组件绑定了myMsg,这样在Input中输入时,Son组件也会发生更新。

子组件向父组件传值

子组件向父组件传值一般通过$emit事件,出发$emit事件,会将参数一同传到监听器的回调。一般有子组件出发$emit事件并传值,由父组件监听。一个$emit事件对应使用一个时间名。

Son.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<template>
<div>
<span>{{msg}}</span>
<button @click='sendtoFather'>clear</button>
</div>
</template>
<script>
export default {
name: 'Son',
data () {
return {}
},
props: {
msg: String
},
methods: {
sendtoFather: function () {
this.$emit('clear')
}
}
}
</script>

在子组件代码中加入向父组件发送消息的事件

1
<button @click='sendtoFather'>clear</button>

该事件见用于清空父组件的myMsg值

父组件也对应添加了事件监听,@clear=’clear’

Father.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<template>
<div>
<Son :msg="myMsg" @clear='clear'></Son>
<input type="text" v-model="myMsg">
</div>
</template>
<script>
import Son from './Son.vue'
export default {
components: {
Son
},
data () {
return {
myMsg: 'Welcome to Your Vue.js App'
}
},
methods: {
clear: function () {
this.myMsg = ''
}
}
}
</script>

兄弟组件传值

兄弟组件传值可以通过共同的父组件作为桥梁来实现,子组件A通过$emit事件将值传到父组件,父组件再通过Props来把值传给子组件B,具体的实现过程参照前面的方法。