【问题标题】:Pass the value of a variable from child component to two parent components, vuejs? nuxt将一个变量的值从子组件传递给两个父组件,vuejs? nuxt
【发布时间】:2020-02-02 12:19:00
【问题描述】:

如何存储变量的状态值?

比如我有三个组件:home.vuemap.vue,还有一个普通的sidebar.vue组件,在home.vuemap.vue里面使用。

我从sidebar.vue(存储侧边栏宽度状态的变量)传递了一些数据。并且这些数据应该在两个组件中动态变化。即从home.vue切换到map.vue时,sidebar.vue的宽度变化变量的状态应该不会改变。

【问题讨论】:

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


【解决方案1】:

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

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

创建商店:

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

使用 store 选项(由 Vue.use(Vuex) 启用)将 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,
  ...
})

通过为根实例提供存储选项,存储将被注入到根的所有子组件中,并在它们上作为this.$store 可用。当宽度改变时,通过在组件的方法中调用突变方法来更新它:

this.$store.commit('setWidth', value)

要在 vue 组件的任何方法中从存储中读取 width 的值,请使用以下命令:

this.$store.state.width

【讨论】:

    猜你喜欢
    • 2019-02-24
    • 2017-05-19
    • 1970-01-01
    • 2020-07-23
    • 2020-02-04
    • 2019-09-15
    • 2017-01-07
    • 2020-11-23
    • 2021-12-27
    相关资源
    最近更新 更多