代码之家  ›  专栏  ›  技术社区  ›  Randy Hall

加载静态数据后初始化Vue

  •  0
  • Randy Hall  · 技术社区  · 7 年前

    我有不需要实时绑定的数据,这些数据来自远程源。这是由服务器从某个管理员处生成的JSON文件,可能会偶尔更新。

    我有一个Vue实例,我希望将该数据用作自定义选项,以避免不必要的反应性绑定。

    我无法在生成中导入.vue文件本身,因为它不会在每次服务器上更改数据时生成。

    如果要加载每个文件(store.json和main.js),这里有一个争用条件,当加载main.js时,可能还没有加载数据,因此我的自定义选项将为空。

    是否存在在存在某些数据之前不初始化的Vue模式?

    尝试:

    export default {
      store: "", 
      mounted(){
        httpRequest = new XMLHttpRequest();
        httpRequest.onreadystatechange = function(){
            if (httpRequest.readyState === XMLHttpRequest.DONE) {
                this.store = JSON.parse(httpRequest.responseText);
                console.log(this.store) //shows the expected return, but obviously no update to the page
            }
        }
        httpRequest.open("GET", "/store.json", true);
        httpRequest.send();    
      }
    };
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Fabian Hijlkema    7 年前

    我曾经遇到过类似的情况,需要在不每次重建项目的情况下调整一些预设。最后我移动了Vue对象,该对象在AsyncAXIOS函数中呈现了应用程序。当然,它会影响加载时间,因为它等待加载JSON文件,在我的例子中,这并不重要。这是此类设置的摘要。

    axios.get('./config.json')
    .then(function(response) {
        let config = response.data
        //commit data to vuex store for example
    
        new Vue({
            store,
            render: h => h(App)
        }).$mount('#app')
    })
    .catch(function(error) {
        console.log(error)
    })
    
    推荐文章