Vue props传入function时的this指向问题_vue props function-CSDN博客

Vue props传入function时的this指向问题

Parent.vue

bash 复制代码
<template>
  <div>
    <Child :func="parentFunc"></Child>
  </div>
</template>

<script>
import Child from './Child'
export default {
  data () {
    return {
      msg: 'this is parent.'
    }
  },
  components: {
    Child
  },
  methods: {
    parentFunc () {
      console.log(this.msg)
    }
  }
}
</script>

Child.vue

bash 复制代码
<template>
  <div>
    <button @click="childFunc">click</button>
  </div>
</template>

<script>
export default {
  props: {
    func: {
      require: false,
      type: Function,
      default: () => {
        return () => {
          console.log(this.msg)
        }
      }
    }
  },
  data () {
    return {
      msg: 'this is child.'
    }
  },
  methods: {
    childFunc () {
      this.func()
    }
  }
}
</script>

踩坑 笔记

  • props传入function时,函数中this自动绑定Vue实例;
  • 在H5的Vue中项目中,console将输出 "this is parent.";
    但在uni-app小程序中使用Vue时,console将输出"this is child";
  • 我的解决方案:
    将父组件msg作为参数传给子组件,子组件props接收msg,然后在父组件的parantFunc中,无论this 指向父组件还是子组件,this.msg总能取得正确的值;
  • 为什么不使用v-on监听子组件事件并用$emit触发事件?
    1. Vue中不推荐向子组件传递Function的方式,因为Vue有更好的事件父子组件通信机制;
    2. 我的原因:项目中的子组件是一个公共组件,原本的代码是使用props+Function的方式,且存在默认值,默认调用函数default默认值;如果改为事件$emit的方式,则涉及修改的地方较多;
    3. 因此,在尽量不影响原来的业务代码的原则下,采用上述解决方案解决该问题;
相关推荐
敲代码的玉米C2 分钟前
测试一直在写你的真实数据根
前端·人工智能·架构
执子念的飞鱼25 分钟前
File Viewer 进入 2K 节点后,我更在意这 3 条回归
前端·typescript
richdata27 分钟前
动态OTB vs 静态OTB:鞋服零售该选哪种管理模式?
前端·html·零售
Jodie同志29 分钟前
第16~23天:持久化、HITL、流式、MCP与安全
前端·后端·agent
Jodie同志34 分钟前
第1~15天:原生Agent、RAG与LangGraph基础(完整代码实操)
前端·后端·agent
sunly_36 分钟前
React useActionState 的用法详解
前端·javascript·react.js
今日无bug37 分钟前
RESTful + Interface:从 todos 项目理解后端接口设计
前端·restful
用户69371750013841 小时前
#DeepSeek+Pi‑Agent 王炸组合跑赢 Claude‑Code!
前端·人工智能·后端
前端一课1 小时前
我还在上班,怎么做一个长期有价值的号
前端
前端一课1 小时前
用 TRAE Work 把项目踩坑经验沉淀成「团队可复用工程规范」,新人再也不重复掉坑
前端·后端