如何在不使用props的情况下将数据从父组件传递到子组件

问题描述 投票:0回答:2

我想编写一个可重用的Vue选项卡组件(我知道那里有很多,但我是为了挑战而这样做)。

我现在面临的问题是在没有使用道具的情况下将数据传递给孩子。

原因很简单,我需要子选项卡元素来了解当前选定的选项卡索引,我不希望使用我的组件的用户总是需要为每个选项卡组件键入props。

由于这个原因,我已经去观察其他Vue标签库如何解决这个问题(bootstrap vuevue tabs等等),但我发现他们都是通过this.$parentthis.$children访问父属性来访问子属性。而且我知道这不是Vue的方式。

我已经研究过注入和提供,这很好但是它没有被动反应。

我也不想使用Vuex,因为我的项目太小而且我希望我的组件可以重用。

有没有更好的方法呢?

javascript vue.js scope vuejs2 vue-component
2个回答
0
投票

一个简单的解决方案是在不使用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,您可以随处访问这个。


-1
投票

我相信学习Vuex可能会引起您的兴趣。 简单来说,Vuex可以作为Vue应用程序中数据的“单一事实来源”。 这意味着存储在vuex“商店”中的任何数据都可以被应用中的任何组件访问。如果将组件设置为正确导入vuex存储,它还会提供对引用存储的任何其他组件的反应绑定,这意味着您不再担心通过多个组件运行复杂的属性传递。相反,每个组件都引用根存储数据。 (希望这很有道理。)

这是一个非常高级别的概述,但如果它听起来对你的项目有帮助,你应该看看Official Documentation这是伟大的!

© www.soinside.com 2019 - 2024. All rights reserved.