1.父组件向子组件传值
父组件可以在引用子组件的时候,通过属性绑定(v-bind:)的形式,把需要传递给子组件的数据,通过属性绑定传递到子组件内部,供子组件使用。
当父组件通过属性绑定将值传过来时,子组件通过props:[ ‘属性值’]接受传过来的属性
父组件代码:
<template>
<div>
<child :parentmsg='msg'></child>//在子组件中通过自定义属性向子组件传值
</div>
</template>
<script>
import child from './child.vue'//引入子组件
export default {
components:{child},//注册子组件
data() {
return {
msg:'我是父组件,给了子组件一个值'
}
},
methods: {
}
}
</script>
子组件代码:
<template>
<div>
父组件传递过来的值:{{parentmsg}}
</div>
</template>
<script>
export default {
props:['parentmsg'],//通过props接收父组件传递过来的值,注意:此处的parentmsg和父组件的自定义属性parentmsg必须一致
data() {
return {
}
},
methods: {
}
}
</script>
最后效果:
2.父组件向子组件传递方法(子组件向父组件传值)
父组件向子组件传递方法,采用的是事件绑定机制(v-on:)。当我们定义完一个事件属性之后,子组件通过this.$emit(‘方法名’)方法调用父组件传递过来的方法。
父组件代码:
<template>
<div>
<child @parentFunction='show'></child>//通过点击事件将父组件定义的show方法传递给子组件,parentFunction名称自定义
</div>
</template>
<script>
import child from './child.vue'
export default {
components:{child},
data() {
return {}
},
methods: {
show(value1,value2){
console.log('父组件的方法')
}
}
}
</script>
子组件代码:
<template>
<div>
<button @click="childClick()">子组件按钮</button>
</div>
</template>
<script>
export default {
props:['parentmsg'],
data() {
return {
}
},
methods: {
childClick(){
this.$emit('parentFunction',value1,value2) //this.$emit的第一个参数是父组件传递过来的方法,后面的所有参数都是子组件向父组件传递的值
}
}
}
</script>