子组件调用父组件的方法:
- 在父组件中给引用的子组件注册一个事件(这个事件的名字是自定义的) 相当于给两个组件直接建立联系
- 子组件可以触发这个事件$emit(‘事件名字’)
子组件给父组件传递数据:
- $emit方法第二个参数可以定义子组件给父组件传递的内容
在父组件中怎么拿到这内容 - 父组件这个方法没有自定参数,在父组件的方法直接加这个参数就可以拿到
- 父组件有自定义参数,可以传入event也可以拿到子组件传递的数据。通过 event也可以拿到子组件传递的数据。通过event也可以拿到子组件传递的数据。通过event只能传递第一个参数。
子传父传值后把值渲染在视图层
子组件为app 父组件为标间father
<div id='app'>
<father></father>
</div>
//自定义father组件
<template id="father">
<div>
<son :toson="toSon" @tofather="tofather($event,1)"></son>
</div>
</template>
//自定义son组件
<template id="son">
<div>
<button @click="toFather">toFather</button>
{{msg}}
</div>
</template>
<script>
//定义father组件
Vue.component('father', {
template: '#father',
data() {
return {
toSon: { name: 1 }
}
},
methods: {
tofather(data, params) {
console.log(data);
console.log(params);
console.log(event);
}
}
})
//自定义son组件
Vue.component('son', {
template: '#son',
data() {
return {
msg: ''
}
},
props: {
toson: [String, Number, Object],
toson: {
type: [String, Number],
dafault() {
return {
}
}
}
},
methods: {
toFather() {
// 第一个参数:自定义事件名 第二个参数:要传递的参数
this.$emit('tofather', '去father', '去father2')
// this.$emit('tofather', { name: 'zs' })
}
},
created() {
// this.$emit('tofather', '去father')
// this.toson = 'father'
// console.log(this.toson);
this.msg = this.toson
}
})
const vm = new Vue({
el: '#app',
data: {
},
methods: {
}
})
</script>
---