簡體   English   中英

如何在不使用道具的情況下將數據從父組件傳遞到子組件

[英]How to pass data from parent to child component without using props

我想編寫一個可重復使用的Vue標簽組件(我知道那里有很多,但是為了挑戰,我正在這樣做)。

我現在面臨的問題是在不使用道具的情況下將數據傳遞給孩子。

原因很簡單,我需要子選項卡元素知道當前選定的選項卡索引,並且我不希望使用我的組件的用戶總是需要為每個選項卡組件輸入道具。

由於這個原因,我去觀察了其他Vue標簽庫如何解決此問題( bootstrap vuevue標簽等),但是我發現的全部是他們使用this.$parentthis.$children訪問父級屬性this.$parent兒童財產。 而且我知道這不是Vue的方式。

我研究了注入和提供,這很棒,但是沒有反應。

我也不想使用Vuex,因為我的項目太小了,我希望組件可重用。

有更好的方法嗎?

一個簡單的解決方案是在不使用Vuex的情況下創建自己的商店:

 class TabStore { constructor() { this.state = { currentIndex: 1 } } setIndex(value) { this.state.currentIndex = value } } let tabStore = new TabStore() Vue.component('tab-item', { template: '#tab', data() { return { state: tabStore.state } } }) new Vue({ el: "#app", data() { return { state: tabStore.state } }, methods: { changeIndex() { let index = Math.floor((Math.random() * 10) + 1) //<-- for the example tabStore.setIndex(index) } } }) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script> <div id="app"> <p>Current Index from Main component: <strong>{{ state.currentIndex }}</strong></p> <tab-item></tab-item> <button @click="changeIndex">Change current index</button> </div> <template id="tab"> <p>Current Index from Tab component: <strong>{{ state.currentIndex }}</strong></p> </template> 

您可以從商店中使用setIndex()來更改state.currentIndex並且可以在任何地方訪問此state.currentIndex

我相信您可能會對學習Vuex感興趣。
簡單來說,Vuex充當Vue應用程序中數據的“單一事實來源”。
這意味着您的應用程序中的任何組件都可以訪問vuex“商店”中存儲的任何數據。 如果您將組件設置為正確導入vuex存儲,它還將提供對任何其他引用該存儲的組件的反應性綁定,這意味着您不再擔心會遇到多個組件之間復雜的屬性傳遞。 而是每個組件都引用根存儲數據。 (希望如此。)

這是一個非常高級的概述,但是如果聽起來對您的項目有幫助,那么您應該真正查看一下官方文檔 ,這很棒!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM