vue-父子组件传值父子组件方法互相调用问题

5次阅读

共计 2039 个字符,预计需要花费 6 分钟才能阅读完成。

传值问题

父传子

父组件

<div>
  <!-- :fatherName 是传到子组件的变量名,fatherName 是父组件的 data 的属性值 -->
  <son-component :fatherName='fatherName' />
</div>
<script>
  name:'father-component',
  data:{
    return:{fatherName:'father-component'}
  },
</script>

子组件

<div>
  {{fatherName}}
</div>
<script>
  name:'son-component',
  props:['fatherName']
</script>

子传父

父组件

<div>
  <!-- :fatherName 是传到子组件的变量名,fatherName 是父组件的 data 的属性值 -->
  <son-component @fatherMethod='fatherMethod' />
</div>
<script>
  name:'father-component',
  methods:{fatherMethod(data){console.log('子组件传值',data)
    }
  }
</script>

子组件

<div>
  <input v-model='sonValue' @change="sendToFather" />
</div>
<script>
  name:'son-component',
  data:{
    return:{sonValue:'',}
  },
  methods:{sendToFather(){// 说白了就是用 this.$emit()调用父组件的方法的同时传值
      this.$emit('fatherMethod',sonValue)
    }
  }
</script>

方法调用问题

父调子

方法一:使用 $refs
父组件

<div>
  <button @click="useSonMethon">click</button>
  <!-- :fatherName 是传到子组件的变量名,fatherName 是父组件的 data 的属性值 -->
  <son-component ref='sonComponent' />
</div>
<script>
  name:'father-component',
  methods:{useSonMethon(){this.$refs.sonComponent.sonMethod()
    }
  }
</script>

子组件

<div>
</div>
<script>
  name:'son-component',
  methods:{sonMethod(){console.log('111')
    }
  }
</script>

子调父

方法一:使用 this$emit()调用父组件方法,参见 传值问题:子传父
方法二:使用 this.$parent
父组件

<div>
  <son-component />
</div>
<script>
  name:'father-component',
  methods:{fatherMethod(){this.$refs.sonComponent.sonMethod()
    }
  }
</script>

子组件

<div>
  <Button @click="useFatherMethod"></Button>
</div>
<script>
  name:'son-component',
  methods:{useFatherMethod(){
      // 注意,我在用的过程中使用 this.$parent 方法时找不到父组件的方法,无意间看到这篇文章 https://segmentfault.com/a/1190000017030948 说是 ui 框架的组件包裹了子组件导致了方法未定义的问题
      this.$parent.fatherMethod()}
  }
</script>

方法三:把父组件方法当参数传给子组件
父组件

<div>
  <!-- :fatherName 是传到子组件的变量名,fatherName 是父组件的 data 的属性值 -->
  <son-component :fatherMethod='fatherMethod' />
</div>
<script>
  name:'father-component',
   methods:{fatherMethod(){this.$refs.sonComponent.sonMethod()
    }
  }
</script>

子组件

<div>
  <Button @click="useFatherMethod"></Button>
</div>
<script>
  name:'son-component',
  props:{
    fatherMethod: {
        type: Function,
        default: null
      }
  },
  methods:{useFatherMethod(){if (this.fatherMethod) {this.fatherMethod();
      }
    }
  }
</script>

补充,如果遇到比较复杂的,多层级组件之间的传值问题,建议使用 vuex 加缓存,否则你马上就会被互相传值、方法互相调用折磨的头皮发麻

正文完
 0