data必须是函数
模板根元素只能一个
模板props中的属性
字符串数组形式
如果是驼峰命名,父组件传值是短横线命名
传值 或 传事件
: props中的属性=“父组件数据”
@子组件事件=“父组件事件”
子组件向父组件传值
因为props中的数据是单向传递的,所以修改不影响父组件数据
子组件调用时,设置:@子组件事件=“父组件事件”
this.$emit(子组件事件函数名(字符串类型),参数)
兄弟组件传值
- 创建事件中心
- 在mouted生命周期函数中注册事件
- 使用eventBus.$on注册,注意要用箭头函数,以免内部无法访问this
- 使用eventBus.$emit触发
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<body>
<div id="components-demo">
<button-counter></button-counter>
<button-counter2></button-counter2>
</div>
</body>
<script>
// 提供事件中心
var eventBus=new Vue();
// 定义一个名为 button-counter 的新组件
Vue.component('button-counter', {
data: function () {
return {
count: 0
}
},
template: '<button v-on:click="handle">clicked me {{ count }}</button>',
methods:{
handle(){
eventBus.$emit('add2',1)
}
},
mounted(){
eventBus.$on('add',(val)=>{
this.count+=val
})
},
})
Vue.component('button-counter2', {
data: function () {
return {
count: 0
}
},
template: '<button v-on:click="handle">clicked me {{ count }}</button>',
methods:{
handle(){
eventBus.$emit('add',2)
}
},
mounted(){
eventBus.$on('add2',(val)=>{
this.count+=val
console.log(this.count);
})
},
})
var app=new Vue({
el:'#components-demo',
data(){
return {
}
}
})
</script>
</html>