Vue.js预先填充数据

时间:2017-03-16 11:45:10

标签: javascript vue.js vuejs2

我有一个带有几个组合框的表单,并且组合框是从REST服务中提取的,但我的问题是工作模型是在组合框所需的任何数据之前加载的,因此组合框永远不会设置为正确的值。

我只有在负载下拉回调中设置负载模型才能使其工作,但这看起来很混乱,如果有多个下拉列表则无法工作。

如何在vue中解决这个问题?

这是脚本

var app = new Vue({
    el: '#categoryEdit',
    data: {
        category: {},
        categories: []
    },
    methods: {
        getCategory: function(categoryId) {
            const config = {
                headers: {
                    'Authorization': 'Bearer ' + '@token'
                }
            };
            axios.get('/api/categories/' + categoryId, config)
                .then(function(response) {
                    app.category = response.data;
                    console.log(app.category);

                })
                .catch(function(error) {
                    alert(error);
                    console.log(error);
                });
        },
        add: function() {
            const config = {
                headers: {
                    'Authorization': 'Bearer ' + '@token'
                }
            };
            axios.post('/api/categories/save', app.author, config);
        },
        fetchCategories: function() {
            var config = {
                headers: {
                    'Authorization': 'Bearer ' + '@token'
                }
            }

            axios.get('/api/categories/all', config)
                .then(function(response) {

                    app.categories = response.data;

                })
                .catch(function(error) {
                    alert(error)
                    console.log(error);
                });
        }
    },
    mounted: function() {
        this.fetchCategories();
        this.getCategory('@ViewContext.RouteData.Values["id"]');
    }
})

这是HTML

<div class="form-group">
    <label class="col-md-3 control-label">Kategorija</label>
    <div class="col-md-9">
        <select class="form-control select2 select2-hidden-accessible" v-model="category.ParentCategoryId">
            <option v-for="cat in categories" :value="cat.Id">
                {{cat.Name}}
            </option>
        </select>
    </div>
</div>

1 个答案:

答案 0 :(得分:2)

尝试在加载所有类别后加载类别:

mounted: function() {
  this.fetchCategories()
    .then(() => {
      this.getCategory('@ViewContext.RouteData.Values["id"]')
    })
}

为此,请确保fetchCategories返回承诺:

fetchCategories: function() {
  var config = {
    headers: {
      'Authorization': 'Bearer ' + '@token'
    }
  }

  return axios.get('/api/categories/all', config)
    .then(response => {
      this.categories = response.data;
    })
    .catch(error => {
      alert(error)
      console.log(error);
    });
}

此外,最好将所有数据绑定到this对象,您不希望您的应用代码知道您如何命名Vue实例变量。

相关问题