首页 文章

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

提问于
浏览
0

我有一个带有几个变量的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并点击根组件时,视图中的更改会突然显示出来?很奇怪

1 回答

  • 1

    对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,
      ...
    

相关问题