Значение v-bind не меняется при изменении данных. Vue.js

У меня есть функция changeActive, которая меняет значение активного логического значения. Но даже несмотря на то, что значение активных изменений (я проверял с помощью console.log), новое значение не передается в v-bind: 'active' дочернему компоненту.

<template>
<div style="width:300px; margin: auto;">
      <RatingLabel 
      :rating='rating[0]'
      :active='active'
      style="margin: auto;"
      />
      <RatingLabel 
      :rating='rating[1]'
      style="float: right;"
      />
      <RatingLabel 
      :rating='rating[2]'
      />
      <RatingLabel 
      :rating='rating[3]'
      style="margin: auto;"
      />
</div>
</template>

<script>
import RatingLabel from '../atomic/RatingLabel'
import { mapState } from 'vuex'
export default {
      components: {
            RatingLabel,
      },

      data() {
            return {
                  active: false,
            }
      },

      methods: {
            changeActive() {
                  setTimeout(function(){ 
                        this.active = !this.active;
                        console.log(this.active)
                   }, 3000);
            }
      },

      mounted() {
            this.changeActive()
      },

      computed: mapState(['rating'])
}
</script>

person Duoro    schedule 14.06.2020    source источник


Ответы (2)


this не определен в функции обратного вызова, вы должны назначить его глобальной переменной vm перед вызовом setTimeout, а затем использовать его внутри обратного вызова:

    changeActive() {
                 let vm=this;
                  setTimeout(function(){ 
                        vm.active = !vm.active;
                        console.log(vm.active)
                   }, 3000);
            }
person Boussadjra Brahim    schedule 14.06.2020

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

function(){} -> () => {}, потому что у вас есть доступ к this

           changeActive() {
                  setTimeout(() => { 
                        this.active = !this.active;
                        console.log(this.active)
                   }, 3000);
person ebyte    schedule 14.06.2020