当前位置: 代码网 > it编程>前端脚本>Vue.js > Vue props传入function时的this指向问题解读

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

2024年05月18日 Vue.js 我要评论
vue props传入function时的this指向parent.vue<template> <div> <child :func="parentfunc"&g

vue props传入function时的this指向

parent.vue

<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

<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触发事件?

  • vue中不推荐向子组件传递function的方式,因为vue有更好的事件父子组件通信机制;
  • 我的原因:项目中的子组件是一个公共组件,原本的代码是使用props+function的方式,且存在默认值,默认调用函数default默认值;如果改为事件$emit的方式,则涉及修改的地方较多;
  • 因此,在尽量不影响原来的业务代码的原则下,采用上述解决方案解决该问题;

vue props 传递函数

props的type是函数

通过 props 传递 函数 看看有啥用。

// 父组件

</template>
 <div>
    <children :add='childrenclick'></children>
    <p>{{countf}}</p>
  </div>
</template>

<script>
import children from './children'
export default {
  name: 'helloworld',
  data() {
    return {
      countf: 0,
    }
  },
  methods: {
    childrenclick(c){
     this.countf += c;
    }
  },
  components:{
    children,
  }
}
</script>

// 子组件
<template>
    <div>
        <button @click="handclick(count)">点击加 1 </button>
    </div>
</template>
<script>
export default {
    data() {
        return {
            count:1,
        }
    },
    props:{
        add:{
            type: function
        }
    },
    methods: {
        handclick(){
            this.add( ++this.count); // 父组件方法
        }
    },
}

结果

可以看到 chirden 组件在中 使用 props.add() , 调用的是 父组件的方法。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com