gpt4 book ai didi

javascript - Vue.js 组件在事件触发后丢失状态

转载 作者:行者123 更新时间:2023-12-01 01:49:09 25 4
gpt4 key购买 nike

我遇到以下问题。在我的 vue 组件中,当从列表中添加或删除项目时,我触发了一个事件。

  export default class HelloWorld extends Vue {
@Prop() private msg!: string;
@Prop() private idCount: number = 0;
@Prop() private toDos: ToDo[] = new Array<ToDo>();
@Prop() private toDoText: ToDoText = new ToDoText();

public NewToDo() {
let element = document.getElementById("NewToDoName") as HTMLInputElement;
let name = element.value;
element.value = "";

var toDo = new ToDo();
toDo.name = name;
toDo.id = ++this.idCount;

this.toDos.push(toDo);
this.$emit('scrollChange');
}

public DeleteToDo(index: number) {
this.toDos.splice(index, 1);
this.$emit('scrollChange');
}
}

所以在我的父组件中我对此事件使用react

<HelloWorld msg="Welcome to your ToDo-App" v-on:scrollChange="onChanged()" class="jumbotron"/>

这就是我的方法

    onChanged(){
this.canScroll = true;
return true;
}

属性canScroll绑定(bind)到另一个子组件

<NavBarBottom v-bind:canScroll="canScroll"/>

我有这个逻辑

<nav class="navbar navbar-expand-lg navbar-dark bg-dark" v-bind:class="[!isFixed ? 'fixed-bottom' : 'bottom']">

export default class NavBarBottom extends Vue {

@Prop() public canScroll : Boolean = false;
@Prop() public isFixed : Boolean = false;

@Watch('canScroll')
onChange(){
//this.isFixed = this.hasVerticalScroll(undefined);
console.log(this.isFixed);
}

private hasVerticalScroll(node : any){
//some checks
}
}

所以,如果我第一次触发该事件,一切都很好。

Component_Fine

但是当我再次将一个项目添加到 HelloWorld-Component 中的数组时,什么也没有发生。当我查看调试器时,组件状态被删除,如下所示:

Component

有人可以解释一下为什么会发生这种情况吗?

感谢您的帮助!

最佳答案

@Prop (vue-property-decorator)的用法所示我相信 Prop 的设置方式可能会导致此问题。请尝试使用default: x而不是定义初始值。所以你的代码看起来像:

@Prop() private msg!: string;
@Prop({ default: 0 }) private idCount: number;
@Prop({ default: new Array<ToDo>() }) private toDos: ToDo[];
@Prop({ default: new ToDoText() }) private toDoText: ToDoText;

关于javascript - Vue.js 组件在事件触发后丢失状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51709331/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com