1

我有一个函数 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>
4

2 回答 2

1

thisvm在回调函数中未定义,您必须在调用之前将其分配给全局变量setTimeout,然后在回调中使用它:

    changeActive() {
                 let vm=this;
                  setTimeout(function(){ 
                        vm.active = !vm.active;
                        console.log(vm.active)
                   }, 3000);
            }
于 2020-06-14T08:42:30.887 回答
0

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);
于 2020-06-14T09:01:54.957 回答