Vue PR ops传入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.'
}
},
component s: {
Child
},
methods: {
parentFunc () {
console. LOG (this.msg)
}
}
}
</script>
Child.vue
<template>
<div>
<button @click="chil DF unc">click</button>
</div>
</template>
<script>
e xp ort default {
props: {
func: {
require: false,
ty PE : 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监听子组件事件并用$em IT 触发事件?
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 f rom './Children'
export default {
n am e: '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() , 调用的是 父组件的方法。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
您可能感兴趣的 文章 : vue中使用props传值的方法 vue父组件通过props如何向子组件传递方法详解 解决vue props传Array/Object类型值,子组件报错的情况
总结
以上是 为你收集整理的 Vue props传入function时的this指向问题解读 全部内容,希望文章能够帮你解决 Vue props传入function时的this指向问题解读 所遇到的问题。
如果觉得 网站内容还不错, 推荐好友。
查看更多关于Vue props传入function时的this指向问题解读的详细内容...