一、属性传值
1.可传值类型
- 固定值
- 绑定属性
- 方法
- 本类对象
2.操作步骤
①.父组件调用子组件的时候,绑定动态属性 <htitle mess="父组件给子组件传值"></htitle>
②. 在子组件里边通过props,接收父组件传过来的值
3.适用场景
仅适用于 父组件给子组件传值
4.属性介绍
组件属性定义:
props:["mess","bindMsg","run","fatherThis"],
子组件验证也可传入参数的合法性:
props:{
'mess':String,
'bindMsg':[String, Number],
'run':Function,
'fatherThis':Object,
}
5.示例代码
父组件:
<template>
<div id="app">
<htitle mess="父组件给子组件传值了" :bindMsg="msg" :run="run" :fatherThis="this"></htitle>
</div>
</template>
子组件
<template>
<div class="divfirst">
<span>{{mess}}</span>
<h1>{{bindMsg}}</h1>
<button @click="run()">点击调用父组件方法</button>
<button @click="getPrasent()">点击获取父组件实体(实体拿到可以使用用父组件的方法和属性了)</button>
</div>
</template>
<script>
export default {
props:{
'mess':String,
'bindMsg':[String, Number],
'run':Function,
'fatherThis':Object,
},
data(){
return {}
},
methods:{
getPrasent(){
this.fatherThis.run();
alert(this.fatherThis.msg);
}
}
}
</script>
二、父组件获取子组件数据
父组件通过$refs获取子组件的数据和方法
1.可获取类型
- 子组件属性
- 子组件方法
2.操作步骤
1.调用子组件的时候调用一个ref
<v-fgsheader ref="header"></v-fgsheader>
2.在父组件中通过
this.$refs.header.属性
this.$refs.header.方法
3.适用场景
子组件给父组件传值
4.示例代码
父组件
<template>
<div class="FGSHome">
<v-fgsheader ref="header"></v-fgsheader>
<button @click="getChildProp()">获取子组件的属性的值</button>
<button @click="getChildMethod()">获取子组件的方法</button>
</div>
</template>
<script>
import FGSHeader from './FGSHeader.vue'
export default{
data(){
return { }
},
components:{
'v-fgsheader':FGSHeader,
},
methods: {
getChildProp(){
alert(this.$refs.header.msg);
},
getChildMethod(){
this.$refs.header.run();
}
},
}
</script>
子组件
<script>
export default{
data(){
return {
msg:"我是子组件header的值哟"
}
},
methods:{
run(){
alert("这是子组件Header的方法+"+this.msg);
}
}
}
</script>
三、子组件获取父组件数据
子组件通过$parent获取父组件的数据和方法,这种传值方式实际上类似于上边的属性传值中父组件给子组件的传递了子类对象this
,只不过Vue官方给封装好了。
1.可获取类型
- 父组件属性
- 父组件方法
2.操作步骤
直接在子组件中使用this.$parent.XX
,不需要做任何多余操作。
3.适用场景
父组件给子组件传值
4.示例代码
子组件
getFatherProp(){
alert(this.$parent.fatherMsg);
},
getFatherMethod(){
this.$parent.fatherRun();
}