将变量的值从子组件传递到两个父组件vuejs? nuxt

时间:2019-10-04 07:20:05

标签: vue.js vue-component nuxt.js

如何存储变量的状态值?

例如,我有三个组件:home.vuemap.vue,以及一个公用的sidebar.vue组件,该组件在home.vuemap.vue内部使用。

我从sidebar.vue(存储边栏宽度状态的变量)中传递了一些数据。并且此数据在两个组件中都应动态更改。也就是说,当从home.vue切换到map.vue时,用于更改sidebar.vue宽度的变量的状态不应更改。

1 个答案:

答案 0 :(得分:0)

您可以将侧边栏的宽度存储在Vuex store中。

  

Vuex是Vue.js应用程序的状态管理模式+库。它充当应用程序中所有组件的集中存储,并具有规则以确保只能以可预测的方式更改状态。

创建商店:

# assert <condition>,<error message>
assert (float(i) > 0) == True, "False"

使用store选项(由Vue.use(Vuex)启用)将存储从根组件“注入”到所有子组件中:

const store = new Vuex.Store({
  state: {
    width: 50
  },
  mutations: {
    setWidth (state, value) {
      state.width = value
    }
  }
})

通过为根实例提供store选项,存储将被注入到根的所有子组件中,并将以const app = new Vue({ el: '#app', // provide the store using the "store" option. // this will inject the store instance to all child components. store, ... }) 的形式在其上可用。更改宽度后,通过在组件的方法中调用mutation方法来更新宽度:

this.$store

要以任何vue组件的方法从存储中读取this.$store.commit('setWidth', value) 的值,请使用以下方法:

width