Vue 2 + Vuex:在计算中使用状态变量 属性

Vue 2 + Vuex: Using state variables in computed property

我有一个带有几个变量的 Vuex 实例:

const store = new Vuex.Store({
  state: {
    start_date: moment().startOf('year').format("MM/DD/YYYY"),
    end_date: moment().format("MM/DD/YYYY")
  },
  mutations: {
    changeDate(state, date_obj) {
      state.start_date = date_obj.start_date
      state.end_date = date_obj.end_date
    }
  }
})

我有我的主要 Vue 实例,其中日期属性继承自 store:

var employees = new Vue({
  el: '#employees',
  computed: {
    start_date() {
      return store.state.start_date
    },
    end_date() {
      return store.state.end_date
    },
    leads() {
      let filter_obj = {
        start_date: this.start_date,
        end_date: this.end_date
      }
      return this.fetch('potential_clients', filter_obj)
    }
  },
  methods: {
    fetch(model, args=null) {
      return new Promise((resolve, reject) => {
        console.log(resolve, reject)
        let url = "/" + model + ".json"
        console.log(url);
        $.ajax({
          url: url,
          data: args,
          success: ((res) => {
            console.log(res)
            this[model] = res;
            resolve(res)
          }),
          error: ((res) => {
            reject(res)
          }),
          complete: (() => {})
        })
      })
    }
  },
  mounted() {
    this.fetch('potential_clients')
  }
});

并且我最初调用 this.fetch('potential_clients') 时没有任何额外参数,但是一旦 start_dateend_date 的值发生更改,我想调用上面的 leads() .但是,当我更改 start_dateend_date.

的值时,没有任何变化

可能值得注意的是,当我使用 Vue 插件在 Chrome 中检查并单击根组件时,突然间视图中显示了更改?很奇怪

对 Vue 实例范围之外的变量的任何引用 will not be reactive。这意味着您引用的 store 对象不是反应性的。

您需要引用 Vue 实例对商店的内部引用 (this.$store), 反应式的:

start_date() {
  return this.$store.state.start_date
},

这是假设您已经在根 Vue 实例的配置对象中传递了 store(在您的示例中似乎是 #employees 组件):

var employees = new Vue({
  el: '#employees',
  store: store,
  ...