Vue.js 2 Невозможно изменить значение свойства данных внутри метода - PullRequest
0 голосов
/ 29 августа 2018

Я пытаюсь обновить taxParentId новым идентификатором, который я получаю с помощью своего вызова API внутри функции getTaxParentId, но я не могу заставить его измениться. Я могу console.log значение отлично внутри метода, но он не будет обновлять его. Кажется, это проблема области видимости, но я позаботился об этом $this = this, однако он не работает.

метод getPostType работает нормально и корректно обновляет значение данных.

var newVue = new Vue({
  el: '#app',
  data() {
    return{
      posts: [],
      taxonomy: '',
      postType: '',
      taxParentSlug: '',
      taxParentId: 0
    }
  },
  created (){
    let $this = this;
    this.getPostType(location.href);
    this.getTaxParent(location.href)
    this.getTaxParentId();
    this.getPosts();

  },
  methods: {
    getPostType: function(currentURL){
        if (currentURL.includes('residential')) {
            this.postType = 'residential';
        }else if(currentURL.includes('commercial')){
            this.postType = 'commercial';
        }else if (currentURL.includes('auto')) {
            this.postType = 'auto';
        }
    },
    getTaxParent: function(currentURL){
        if (currentURL.includes('solar')) {
            this.taxParentSlug = 'solar';
        }else if(currentURL.includes('decorative')){
            this.taxParentSlug = 'decorative';
        }else if (currentURL.includes('safety-security')) {
            this.taxParentSlug = 'safety-security';
        }
    },
    getTaxParentId: function(){
        let $this = this;

        axios
          .get(apiRoot + $this.postType + '-categories')
          .then(function (response) {
            response.data.forEach(function(item){
                if (item.slug == $this.taxParentSlug) {
                    $this.taxParentId = item.id;
                }
            });
          }
        )
    },
    getPosts: function(){
        let $this = this;

        console.log(apiRoot + $this.postType + '-categories?parent=' + $this.taxParentId)
        axios

          .get(apiRoot + $this.postType + '-categories?parent=' + $this.taxParentId)
          .then(function (response) {
            $this.posts = response.data;
            console.log($this.posts)
          }
        )
    },
  },

});

Ответы [ 2 ]

0 голосов
/ 30 августа 2018

Поскольку вы уже используете обещания, вы сможете создать цепочку обещаний для решения асинхронной проблемы.

Возьмите свою текущую функцию: `` `Javascript getTaxParentId: function () { пусть $ this = this;

    axios
      .get(apiRoot + $this.postType + '-categories')
      .then(function (response) {
        response.data.forEach(function(item){
            if (item.slug == $this.taxParentSlug) {
                $this.taxParentId = item.id;
            }
        });
      }
    )
},

и заставить его возвращать значение, даже если это просто ответ `` `Javascript getTaxParentId: function () { пусть $ this = this;

    axios
      .get(apiRoot + $this.postType + '-categories')
      .then(function (response) {
        response.data.forEach(function(item){
            if (item.slug == $this.taxParentSlug) {
                $this.taxParentId = item.id;
            }
        });
        return response
      }
    )
},

Затем в вашей функции created() вы можете связать вызов ..

created (){
    let $this = this;
    this.getPostType(location.href);
    this.getTaxParent(location.href)
    this.getTaxParentId()
     .then(function (response) {
        this.getPosts();
    })
  },

Это должно заставить this.getPosts() ждать завершения getTaxParentId.

0 голосов
/ 29 августа 2018

Из-за асинхронности добавьте наблюдателей к своим данным и войдите в систему.

watch:{
    posts(value){console.log(value))},
    taxParentId(value){console.log(value))}
}

В идеале вы будете получать обещание от каждого звонка, а затем ждать их всех. Если один вызов зависит от другого, вам нужно поместить второй вызов в блок then () или, что еще лучше, дождаться его (async / await)

Используя это, все, что вам нужно сделать, это вернуть обещание, и оно будет синхронизировано.

  async created (){
    let $this = this;
    await this.getPostType(location.href);
    await this.getTaxParent(location.href)
    await this.getTaxParentId();
    await this.getPosts();
  },

Так чище, чем цепочка then блоков. Вы можете обернуть весь блок в ОДИНОЧНЫЙ улов и поймать все исключения И все отклонения. Конечно, если вызовы не являются зависимыми, вы можете вызывать их параллельно и не ждать.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...