父组件传子组件
<div id='app'>
<!-- 父传子需要在父组件中的子组件中定义一个变量 -->
<son :type="father"></son>
</div>
<template id="son">
<div>
{{type}}
</div>
</template>
<script>
// 子组件
Vue.component('son',{
template:'#son',
// 在子组件中需要用props接收父组件的值
props:{
type:[String,Number]
},
})
// 父组件
const vm = new Vue({
el: '#app',
data: {
father:'父组件传给子组件的值'
},
methods: {
}
})
</script>
子组件传父组件
<div id='app'>
<!-- 子传父需要在父组件中的子组件中定义一个自定义事件 -->
<son @getson="getson"></son>
<h2>{{msg}}</h2>
</div>
<template id="son">
</template>
<script>
// 子组件
Vue.component('son',{
template:'#son',
data(){
return {
msg:'子传过来的值'
}
},
created(){
// 在子组件中用this.$emit传递参数 this.$emit(第一个参数 自定义事件的名字,第二个参数 传递的值)
this.$emit('getson',this.msg)
}
})
// 父组件
const vm = new Vue({
el: '#app',
data: {
msg:''
},
methods: {
// 自定义的事件名函数接收子传过来的值
getson(data){
this.msg = data
}
}
})
</script>