我正在與BootstrapVue.
我有一個方法parent.vue,我將一個值 ( this.propsIndex)傳遞給我的child.vue.
現在我想value每次在我的 child.vue 的方法中點擊它時都使用它 - 但是我如何觸發我的功能并使其作業?
非常感謝!
如果可能的話,我想避免使用 watch
我的父母.vue
<template>
<div v-for="(id, index) in inputs" :key="index">
<b-button @click="deleteViaIndex(index)">Delete</b-button>
<child :indexProps="indexProps" />
</div>
<div>
<b-button @click="addInput()">Add Input</b-button>
</div>
</template>
<script>
methods: {
deleteViaIndex(index) {
this.propsIndex= index;
},
addInput() {
this.inputs.push({})
},
},
data() {
return {
inputs: [{}],
propsIndex: '',
}
}
</script>
我的 child.vue(腳本)
props: ["propsIndex"],
methods: {
deleteViaParentIndex() {
//HERE I WANT TO USE IT EVERY TIME IT WILL BE CLICKED IN MY PARENT.VUE
//BUT FOR NOW IT'S NOT DOING ANYTHING WHEN I CONSOLE.LOG(this.propsIndex)
}
}
uj5u.com熱心網友回復:
看起來像命名不匹配。在子組件中,您有一個 prop propsIndex,但在父模板中您正在傳遞indexProps。
傳遞 props 時,你必須記住,prop name 總是在第一部分,你傳遞的 value 應該放在后面。https://vuejs.org/v2/guide/components-props.html#Passing-Static-or-Dynamic-Props
此外,由于 HTML 屬性名稱不區分大小寫,您應該通過以下方式傳遞 prop:
<child :props-index="indexProps" />
uj5u.com熱心網友回復:
除了 Marcin 提到的命名不匹配之外,您可以使用模板中的ref從父組件訪問子組件:
<child ref="childrenComponents" :props-index="propsIndex" />
既然你有多個內的子組件v-for,這使得childrenComponents在$refs組件的陣列。要呼叫deleteViaParentIndex所有這些,您需要遍歷它們:
deleteViaIndex(index) {
this.propsIndex = index;
this.$refs.childrenComponents.each(child => child.deleteViaParentIndex());
}
您還可以進行一項優化。
由于您propsIndex僅用于傳遞子組件使用的索引,并且您已經將索引作為引數deleteViaIndex傳入,因此您可以在deleteViaParentIndex函式呼叫期間將其作為引數簡單地傳遞給子組件,從而消除對propsIndex資料的需要共:
在parent.vue:
deleteViaIndex(index) {
this.$refs.childrenComponents.each(child => child.deleteViaParentIndex(index));
}
在child.vue:
deleteViaParentIndex(index) {
// operations using index
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/332934.html
標籤:javascript Vue.js Vuejs2 成分
