【问题标题】:Value of v-bind is not changing when data changes. Vue.js [duplicate]当数据改变时 v-bind 的值不会改变。 Vue.js [重复]
【发布时间】:2020-10-03 19:09:48
【问题描述】:

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

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component vue-props


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      function(){} -> () =&gt; {},因为可以访问this

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

      【讨论】:

        猜你喜欢
        • 2022-01-12
        • 2018-12-20
        • 2020-08-26
        • 2017-02-25
        • 2022-08-19
        • 1970-01-01
        • 2019-05-11
        • 2015-06-09
        • 1970-01-01
        相关资源
        最近更新 更多