详解Vue组件之间通信的七种方式

2020-06-14 06:07:16易采站长站整理

}
},
methods: {
amend() {
this.$parent.title = '修改后的父组件标题';
}
}
}
</script>
```

3)自定义事件的v-model

https://cn.vuejs.org/v2/guide/components-custom-events.html#%E8%87%AA%E5%AE%9A%E4%B9%89%E7%BB%84%E4%BB%B6%E7%9A%84-v-model
具体

  


```
// 父组件
<template>
<div>
标题:<input type="text" v-model="mymessage"><br />
<Children v-model="mymessage" />
</div>
</template>

<script>
import Children from './children.vue';
export default {
data() {
return {
mymessage: '名字',
}
},
components: {
Children
}
}
</script>
// 子组件
<template>
<div>
<input type="text" :value="mymessage" @input="changeValue">
</div>
</template>

<script>
export default {
model: {
prop: 'mymessage',
event: 'input'
},
props: ['mymessage'],
methods: {
changeValue(event){
this.$emit('input', event.target.value);
}
}
}
</script>
```

祖先组件和其子孙组件通信

1)provide/inject

provide/inject,允许一个祖先组件向其所有子孙后代注入一个依赖,不论组件层次有多深,并在起上下文关系成立的时间里始终生效

https://cn.vuejs.org/v2/api/#provide-inject     

具体

   


```
// 父组件
<template>
<div>
<h3>{{title}}</h3>
<Children />
</div>
</template>

<script>
import Children from './children.vue';
export default {
data() {
return {
title: '父组件的标题'
}
},
provide() {
return {
updateTitle: this.updateTitle
}
},
methods: {
updateTitle(title) {
this.title = title;
}
},
components: {
Children
}
}
</script>
// 子组件
<template>
<div>
<button @click="changeAttr">修改父组件的属性</button>
<Grandson />
</div>
</template>

<script>