我正在使用vue3
与options api
如下面发布的代码所示,当单击checkbox
时,onToggleBtnClearDigitizedChanged()
被调用,导致state
从false
更改为true
,并且对于下面的行,使用相同的方法:
this.compPropsVModelToggleClearDigitizedBtn = this.state;
我将分配给this.satate
的新值分配给this.compPropsVModelToggleClearDigitizedBtn
,它应该是true
,但令人惊讶的是,log语句
console.log('##compPropsVModelToggleClearDigitizedBtn:' + this.compPropsVModelToggleClearDigitizedBtn);
打印this.compPropsVModelToggleClearDigitizedBtn
的值是false
。这怎么可能因为this.state = !this.state
,然后this.state
的值被分配给this.compPropsVModelToggleClearDigitizedBtn
**代码链接:
输出:
验证码:
<template>
<cds-toggle id="idToggleBtnClearDigitized" class="clsToggleBtnDigitizePolygon">
<label for="toggling-digitization-of-polygon-on-and-off">
{{ toggleBtnClearDigitizedLabel }}
</label>
<input
type="checkbox"
:value="compPropsVModelToggleClearDigitizedBtn"
@input="$emit('update:compPropsVModelToggleClearDigitizedBtn', $event.target.value)"
:disabled="isToggleBtnClearDigitizedDisabled"
@change="onToggleBtnClearDigitizedChanged()"
:checked="compPropsVModelToggleClearDigitizedBtn"
/>
</cds-toggle>
</template>
<script>
export default {
data() {
return {
state: false,
};
},
props: {
toggleBtnClearDigitizedLabel: {
type: String,
default: 'clear',
},
isToggleBtnClearDigitizedDisabled: {
type: Boolean,
default: false,
},
vModelToggleClearDigitized: {
type: undefined,
default:true
},
},
emits: ['update:vModelToggleClearDigitized'],
computed: {
compPropsVModelToggleClearDigitizedBtn: {
get() {
console.log('get.compPropsVModelToggleClearDigitizedBtn:' + this.vModelToggleClearDigitized);
return this.vModelToggleClearDigitized;
},
set(value) {
console.log('set.compPropsVModelToggleClearDigitizedBtn:' + value);
this.$emit('update:vModelToggleClearDigitized', value);
},
},
},
watch: {
isToggleBtnClearDigitizedDisabled(newVal, oldVal) {
console.log( 'watch.isToggleBtnClearDigitizedDisabled.newVal:' + newVal);
console.log('watch.isToggleBtnClearDigitizedDisabled.oldVal:' + oldVal);
},
state(newVal, oldVal) {
console.log( 'watch.state.newVal:' + newVal);
console.log('watch.state.oldVal:' + oldVal);
}
},
methods: {
onToggleBtnClearDigitizedChanged() {
this.state = !this.state
this.compPropsVModelToggleClearDigitizedBtn = this.state;
console.log('##state:' + this.state);
console.log('##compPropsVModelToggleClearDigitizedBtn:' + this.compPropsVModelToggleClearDigitizedBtn);
if (this.compPropsVModelToggleClearDigitizedBtn == true) {
setTimeout(() => {
this.compPropsVModelToggleClearDigitizedBtn = false
}, 3000);
}
},
},
};
</script>
1条答案
按热度按时间s3fp2yjn1#
出现此问题是因为您在更新
this.compPropsVModelToggleClearDigitizedBtn
后立即记录了它的值。由于Vue的异步特性, prop 更新不会立即生效。为了确保记录的是更新后的值,可以利用Vue的
nextTick
方法来等待DOM更新以记录新值。更新onToggleBtnClearDigitizedChanged
方法如下:还有一件事这些名字是我一生中见过的最长的名字😂!为了代码更简洁,请考虑使用更短的变量名。🌷
希望这对你有帮助!