Vue?props傳入function時的this指向問題解讀
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時,函數(shù)中this自動綁定Vue實例;
在H5的Vue中項目中,console將輸出 “this is parent.”;
但在uni-app小程序中使用Vue時,console將輸出“this is child”;
我的解決方案
將父組件msg作為參數(shù)傳給子組件,子組件props接收msg,然后在父組件的parantFunc中,無論this 指向父組件還是子組件,this.msg總能取得正確的值;
為什么不使用v-on監(jiān)聽子組件事件并用$emit觸發(fā)事件?
- Vue中不推薦向子組件傳遞Function的方式,因為Vue有更好的事件父子組件通信機制;
- 我的原因:項目中的子組件是一個公共組件,原本的代碼是使用props+Function的方式,且存在默認(rèn)值,默認(rèn)調(diào)用函數(shù)default默認(rèn)值;如果改為事件$emit的方式,則涉及修改的地方較多;
- 因此,在盡量不影響原來的業(yè)務(wù)代碼的原則下,采用上述解決方案解決該問題;
Vue props 傳遞函數(shù)
Props的type是函數(shù)
通過 props 傳遞 函數(shù) 看看有啥用。
// 父組件
</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() , 調(diào)用的是 父組件的方法。
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
VUE+node(express)實現(xiàn)前后端分離
在本篇文章里小編給大家分享的是關(guān)于VUE+node(express)前后端分離實例內(nèi)容,有需要的朋友們參考下。2019-10-10
一文詳解VueUse中useAsyncState的實現(xiàn)原理
在Vue 3 Composition API中,我們可以使用自定義鉤子函數(shù)來封裝可復(fù)用的邏輯,useAsyncState是一個用于管理異步狀態(tài)的自定義鉤子函數(shù),本文將給大家介紹一下useAsyncState的實現(xiàn)原理,感興趣的朋友可以參考下2024-01-01
vue表單驗證rules及validator驗證器的使用方法實例
在vue開發(fā)中,難免遇到各種表單校驗,下面這篇文章主要給大家介紹了關(guān)于vue表單驗證rules及validator驗證器使用的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-07-07
vite+vue3項目集成ESLint與prettier的過程詳解
這篇文章主要介紹了vite+vue3項目中集成ESLint與prettier的相關(guān)知識,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-09-09

