父传子
父子传值一般在子组件上绑定自定义的属性,然后子组件在实例中通过props接收该属性
app.vue1
<brother :name="name" />
brothe.vue1
2
3
4
5
6
7
8
9export default {
name:'brother',
props:['name'],
data () {
return {
};
}
}
子传父
一般使用emit反向传值,通过注册自定义事件,在事件函数中接收值
brother.vue1
2
3
4
5<template>
<div>
<div @click="aaa">click</div>
</div>
</template>
1 | export default { |
app.vue1
2
3
4
5
6
7<template>
<div>
//在对应的子组件上,绑定自定义事件
//事件被触发后,会调用bbb()函数
<brother @custom-event="bbb" />
</div>
</template>
1 | export default { |
非父子组件间
建立一个公共的js文件,作为中间仓库来传值
公共bus.js1
2import Vue from 'vue'
export default new Vue()
组件A1
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>
// A组件:
<span>{{elementValue}}</span>
<input type="button" value="点击触发" @click="elementByValue">
</div>
</template>
<script>
// 引入公共的bug,来做为中间传达的工具
import Bus from './bus.js'
export default {
data () {
return {
elementValue: 4
}
},
methods: {
elementByValue: function () {
Bus.$emit('val', this.elementValue)
}
}
}
</script>
组件B1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31<template>
<div>
B组件:
<input type="button" value="点击触发" @click="getData">
<span>{{name}}</span>
</div>
</template>
<script>
import Bus from './bus.js'
export default {
data () {
return {
name: 0
}
},
mounted: function () {
var vm = this
// 用$on事件来接收参数
Bus.$on('val', (data) => {
console.log(data)
vm.name = data
})
},
methods: {
getData: function () {
this.name++
}
}
}
</script>