如何使组件数据等于全局对象

时间:2017-08-19 18:29:16

标签: vue.js vuejs2

我希望我的组件共享一个全局数据,这是一个全局变量,在我的主Vue实例挂载时通过ajax设置。但是,当我尝试在下面的代码中设置它时,组件数据为空。我如何将组件的数据设置为等于共享的全局对象?

如果这是一个ajax问题,我如何让组件等待tableData设置或让我的组件监视tableData进行更改?

//Snippet of what gets return from ajax call
{
  121: {
    table_info: {
    id: "121",
    name: "Test",
    table_number: "51",
    cap: "6",
    seating: "OPEN",
    position_x: "0.19297285",
    position_y: "0.07207237",
    participants_in_tables: "5",
    count: 5
   }
 }
}

//Global
var tableData; //This gets set when the Vue ajax call is complete after being mounted
var width = $(document).width();
var height = $(document).height();

//Vue
Vue.component('tables', {
      data: () => {
        return {
          tables: tableData
        }
      },
      template: `
                <div id="tableContain">
                    <div class='table' v-for="table in tables" :style="computeOffsets(table)">
                        {{table.table_info.name}}
                    </div>
                </div>
            `,
      methods: {
        computeOffsets(table) {
          return {
            top: (table.table_info.position_x * width) + 'px',
            left: (table.table_info.position_y * height) + 'px'
          }
        }
      });

    var app = new Vue({
      el: '#main',
      mounted() {
        $.ajax({
          method: 'POST',
          dataType: 'json',
          url: base_url + 'users/getTableAssignments/' + event_id
        }).done(data => {
          tableData = data; //Set global tableData 
        });
      }
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>
<div id="main">
  <table></table>
</div>

1 个答案:

答案 0 :(得分:1)

最好的方法是使用vuex https://vuex.vuejs.org/en/intro.html

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    tableData: {}
  },
  mutations: {
    setData (state, tableData) {
      state.tableData = tableData
    }
  },
  actions: {
    getData ({commit}, event_id) {
      $.ajax({
          method: 'POST',
          dataType: 'json',
          url: base_url + 'users/getTableAssignments/' + event_id
        }).done(data => {
            commit('setData', {tableData})
        });
    }
  },
  getters: {
    tableData (state) {
      return state.tableData
    }
  }
})

您可以按this.$store.dispatch('getData', event_id)

在组件中触发此操作

tableData移除data(),现在在计算属性中获取this.$store.getters.tableData的数据:

computed: {
  computedTableData () {
    return this.$store.getters.tableData
  }
}

为了便于调试,请安装https://chrome.google.com/webstore/detail/vuejs-devtools/nhdogjmejiglipccpnnnanhbledajbpd?hl=en