父组件获取子组件中的属性和方法
父组件可以修改子组件的属性
this.$refs.header.msg='在父组件修改'
子组件也可以修改父组件的属性
this.$parent.age='我是在子组件修改父组件'
一、this.$refs//父组件获取子组件的方法和属性
具体实现
1.在引入的子组件上设置ref属性
<hellWord :title='title' @uppta='setTitle' ref="header"></hellWord>
2.在方法中获取
this.$refs.header.msg//获取属性
this.$refs.header.open()/获取方法
子组件获取父组件的属性和方法
this.$paren 这就话应该是获取父组件,因为我使用了element-ui 将我的子组件包了起来,获取到的父组件就是element-ui了,所以在调用父组件的方法是肯定是没有了
this. p a r e n t . parent. parent.parent.homeVistTask() //这样就可以正常拿到父组件中的方法了~
this.$parent.age//获取属性
this.$parent.run()//获取方法
父给子传参
父组件
下面展示一些 内联代码片
。
<template>
<div style="margin-top:60px;">
<h2>父组件</h2>
<Index :son="mes"></Index>
</div>
</template>
<script>
import Index from "./index"
export default {
name:"DataFunnel",
components:{
Index
},
data(){
return{
mes:"大嘴巴子"
}
},
methods:{
}
}
</script>
<style>
</style>
子组件
<template>
<div style="margin-top:60px;">
<h2>子组件</h2>
<button >woshizizujian</button>
<p>{{son}}</p>
</div>
</template>
<script>
export default {
props:["son"],
},
子组件给父组件传参
子组件
<template>
<div style="margin-top:60px;">
<h2>子组件</h2>
<button @click="toParent">给父子间传参</button>
<p>{{son}}</p>
</div>
</template>
<script>
export default {
props:["son"],
data(){
return{
mony:"100万"
}
},
methods:{
toParent(){
this.$emit('from',this.mony)
}
}
}
</script>
<style>
</style>
父组件
<template>
<div style="margin-top:60px;">
<h2>父组件</h2>
<Index :son="mes" @from="open"></Index>
<p>儿子给了爸爸{{mony}}</p>
</div>
</template>
<script>
import Index from "./index"
export default {
name:"DataFunnel",
components:{
Index
},
data(){
return{
mes:"大嘴巴子",
mony:""
}
},
methods:{
open(data){
this.mony=data
}
}
}
</script>
<style>
</style>
vue中实现双向数据通信
这个往往是使用在弹窗,子组件是一个弹窗页
父组件中
//把弹窗封装成一个组件引入,注册,使用
import Demo from './demo'
components:{
Demo
},
//必须要加v-if, 刚开始默认是不显示把父组件的false传给子组件 子组件关闭需要更改父组件的状态
<Demo v-if="showDan" :showDan='this.showDan' @update='showDanChuang'></Demo>
//父组件中的方法
showDanChuang(value){
this.showDan=value
},
子组件
export default {
props:['showDan'],
name: "demo.vue",
data() {
return {
dialogVisible: this.showDan
};
},
mounted(){
console.log(this.showDan);
},
methods: {
cancel(){
this.dialogVisible=false
this.$emit('update',false)
}
}
}
子组件中触发父组件的自定义事件
this.$emit('方法名')
兄弟组件之间通信,a组件给b组件传递参数
1.创建一个bus.js文件
// 导入vue
import Vue from 'vue';
// 导出bus
export default new Vue();
//(没错,这个文件就两行代码)
第二步在a组件中设置要传递给b组件的方法和数据
//在login.vue组件中使用到bus,就在vue中导入bus文件
//导入 bus.js
<script>
import bus from 文件路径/bus.js
export default {
methods:{
openreply(){ //在这里随意写一个方法
// 通过eventbus 向(兄弟组件)中传入数据源 (值)
bus.$emit('passitem', this.commentItem)
}
}
</script>
第三步b组件中接收
//在home.vue组件(兄弟)接收login.vue兄弟传过来的值
<script>
//导入bus.js
import bus from 文件路径/bus.js
export default {
created() {
// $on 接收comment兄弟组件传的参数
bus.$on("passitem", value => {
this.commentItem = value; //value就是comment组件传过来的commentItem
});
},
}
</script>