目录
1.父传后代 ( 后代拿到了父的数据 )
1. 父组件引入子组件,绑定数据
<List :str1=‘str1’></List>
子组件通过props来接收
props:{
str1:{
type:String,
default:''
}
}
***这种方式父传子很方便,但是父传给孙子辈分的组件就很麻烦(父=》子=》孙)
这种方式:子不能直接修改父组件的数据
2. 子组件直接使用父组件的数据
子组件通过:this.$parent.xxx使用父组件的数据
这种方式:子可以直接修改父组件的数据
3. 依赖注入(使用 provide/inject API)
优势:父组件可以直接向某个后代组件传值(不让一级一级的传递)
1.在祖先组件中使用 provide
在祖先组件中,你可以使用 provide 选项来提供数据或方法。这些数据或方法可以被任何后代组件通过 inject 选项来接收。
<!-- AncestorComponent.vue -->
<template>
<div>
<DescendantComponent />
</div>
</template>
<script>
import DescendantComponent from './DescendantComponent.vue';
export default {
components: {
DescendantComponent
},
provide() {
return {
foo: 'foo',
myMethod: this.myMethod
};
},
methods: {
myMethod() {
console.log('This is a metho