目录Vue props传入function时的this指向踩坑笔记我的解决方案Vue props 传递函数Props的type是函数总结Vue props传入function时的th
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触发事件?
通过 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() , 调用的是 父组件的方法。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。
--结束END--
本文标题: Vue props传入function时的this指向问题解读
本文链接: https://www.lsjlt.com/news/178278.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-01-12
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0