【问题标题】:How can I reactively update a value in a component from a store value?如何从存储值响应式更新组件中的值?
【发布时间】:2019-08-16 03:33:12
【问题描述】:

根据此处的文档,我有两个组件和一个基本存储:https://vuejs.org/v2/guide/state-management.html#Simple-State-Management-from-Scratch

我想这样做,以便当我输入输入时,使用商店更新不同组件中的值。

这里是基本示例。

App.vue

<template>
  <div id="app">
    <h1>Store Demo</h1>
    <BaseInputText /> Value From Store: {{ test }}
  </div>
</template>

<script>
import BaseInputText from "./components/BaseInputText.vue";
import { store } from "../store.js";

export default {
  // This should reactively changed as per the input
  computed: {
    test: function() {
      return store.state.test;
    }
  },
  components: {
    BaseInputText
  }
};
</script>

BaseInput.vue

<template>
  <input type="text" class="input" v-model="test" />
</template>

<script>
import { store } from "../store.js";

export default {
  data() {
    return {
      test: store.state.test
    };
  },
  // When the value changes update the store
  watch: {
    test: function(newValue) {
      store.setTest(newValue);
    }
  }
};
</script>

store.js

export const store = {
  debug: true,
  state: {
    test: "hi"
  },
  setTest(newValue) {
    if (this.debug) console.log("Set the test field with:", newValue);
    this.state.test = newValue;
  }
};

我想这样当我在输入中输入一个字符串时,App.vue 中的test 变量会被更新。我试图了解商店模式是如何工作的。我知道如何使用道具。

我这里也有一份工作副本:https://codesandbox.io/s/loz79jnoq?fontsize=14

【问题讨论】:

  • 如果你想更新store的状态,你应该使用mutations。直接修改 store 是一种反模式,你会看到一个关于它的控制台警告。
  • 这适用于文档中引用的商店模式。抱歉,vuex 标签有点误导。

标签: javascript vue.js vuejs2


【解决方案1】:

更新
2.6.0+
使用 Vue.observable(在 2.6.0+ 中添加)使商店反应式使用

store.js

import Vue from 'vue'

export const store = Vue.observable({
  debug: true,
  state: {
    test: 'hi'
  }
})

BaseInputText.vue

<input type="text" class="input" v-model="state.test">
...
data() {
    return {
      state: store.state
    };
  },

2.6.0 之前

store.js

import Vue from 'vue'

export const store = new Vue({
  data: {
    debug: true,
    state: {
      test: 'hi'
    }
  }
})

BaseInputText.vue

<input type="text" class="input" v-model="state.test">
...
data() {
  return {
    state: store.state
  };
}

旧答案
来自文档However, the difference is that computed properties are cached based on their reactive dependencies. 商店没有反应

改成

App.vue

  data() {
    return {
      state: store.state
    };
  },
  computed: {
    test: function() {
      return this.state.test;
    }
  },

它看起来很糟糕,但我没有看到其他方法来让它工作

【讨论】:

  • 我看到了你的第一个答案,这实际上更接近正确。我对其进行了更改,以便不再直接引用存储值,而是引用状态。即 {{ state.test }} 而不是 {{ test }}。如果你改回来,我会接受答案:)。
  • 它对你有用吗?我重新加载了页面,但它不适合我)您可以使用 observable 看到更清晰的解决方案(需要 2.6 版)
  • 是的,如果进行随机更改然后将它们改回来,它似乎可以工作。诡异的。我喜欢你的新解决方案,但我还没有使用 2.6。因此,澄清整体问题与直接引用商店中的值有关。
  • 更新了 vue 之前版本的解决方案。感谢您提出有趣的问题。
猜你喜欢
  • 1970-01-01
  • 2020-07-30
  • 1970-01-01
  • 2020-11-12
  • 2020-10-27
  • 1970-01-01
  • 1970-01-01
  • 2023-04-11
  • 2020-07-22
相关资源
最近更新 更多