父组件给子组件传值
1,传静态值
父组件引用子组件com并且传了一个值age
<com age="age"/>
<template>
<div class="com">
child components
{{age}}
</div>
</template>
<script>
export default{
props:['age'],
data(){
return{
}
}
}
</script>
<style>
</style>
结果
2、传动态值,
只是父组件在传值时,申明的名字前要加冒号,子组件里面的写法不变
<com :age="age"/>
data(){
return{
age:180
}
}
结果:
子组件调用父组件的方法
示例:
子组件com
<button type="button" name="button" @click="$emit('patch')">发送到父组件</button> <!-- 点击button调用父组件的patch方法 -->
父组件
<com :age="age" @patch = "buttonClick"/>
data(){
return{
age:180
}
},
methods:{
buttonClick:function(){
this.age++
}
}
通过点击子组件来改变父组件的age,
子组件可以通过方法传参把值传给父组件
<button type="button" name="button" @click="$emit('patch',34)">发送到父组件</button> <!-- 点击button调用父组件的patch方法 -->
methods:{
buttonClick:function(a){
this.age++
window.console.log(a)
}
}
插槽
示例:
子组件
<template>
<div class="com">
child components
{{age}}
<button type="button" name="button" @click="$emit('patch',34)">发送到父组件</button>
<slot></slot>
</div>
</template>
父组件
通过插槽slot的方式,让父组件在引用子组件时,还可以在组件内部添加新的东西
如果有多个地方需要使用插槽,可以给slot命名来区分
示例:
子组件
<template>
<div class="com">
<slot name="head"></slot>
<button type="button" name="button" @click="$emit('patch',34)">发送到父组件</button> <!-- 点击button调用父组件的patch方法 -->
<slot name="bottom"></slot>
</div>
</template>
父组件
<com :age="age" @patch = "msg">
<h1 slot="head">我是新加入的头部内容</h1>
<h1 slot="bottom">我是新加入底部的内容</h1>
</com>
结果