v-bind 的值在数据更改时不会更改。 Vue.js
Value of v-bind is not changing when data changes. Vue.js
我有一个函数 changeActive 可以改变 active 布尔值。但即使活动值发生变化(我使用 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>
this
在回调函数中未定义,必须在调用setTimeout
之前将其赋值给全局变量vm
,然后在回调函数中使用它:
changeActive() {
let vm=this;
setTimeout(function(){
vm.active = !vm.active;
console.log(vm.active)
}, 3000);
}
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);
我有一个函数 changeActive 可以改变 active 布尔值。但即使活动值发生变化(我使用 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>
this
在回调函数中未定义,必须在调用setTimeout
之前将其赋值给全局变量vm
,然后在回调函数中使用它:
changeActive() {
let vm=this;
setTimeout(function(){
vm.active = !vm.active;
console.log(vm.active)
}, 3000);
}
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);