gpt4 book ai didi

javascript - vue.js - 在事件发生后更改按钮内的文本

转载 作者:数据小太阳 更新时间:2023-10-29 05:24:45 25 4
gpt4 key购买 nike

我正在玩 vue.js 用于学习目的,它由不同的组件组成,其中之一是经典的待办事项列表。目前,一切都在一个组件中。

我想在单击按钮以将元素从“隐藏”隐藏为“显示”后更改按钮的文本 - 我将通过设置文本数据对象然后在函数中更改它来解决这个问题。

见下文:

<div id="app">
<ul>
<li v-for="todo in todos">
{{ todo.text }}
</li>
</ul>

<input type="text" id="list-input">
<input type="submit" id="list-submit" v-on:click="addItem">
<span id="error" style="color: red; display: none;">Please Enter Text</span>

<ul>
<todoitem></todoitem>
<todoitem></todoitem>
<todoitem></todoitem>
</ul>

<h2 v-if="seen">SEEN</h2>
<button id="hide-seen" v-on:click="toggleSeen">{{ button.text }}</button>
</div>

<script type="text/javascript">
// components
Vue.component('todoitem', {
template: "<li>Test Item</li>"
})

// app code
var app = new Vue({
el: '#app',
data: {
todos: [
{ text: 'Sample Item 1' },
{ text: 'Sample Item 2' },
{ text: 'Sample Item 3' }
],
button: [
{ text: 'Hide'}
],
seen: true
},
methods: {
addItem: function() {
let item = document.getElementById("list-input").value;
let error = document.getElementById("error");
if (item == "") {
error.style.display = "block";
} else {
app.todos.push({ text: item });
error.style.display = "none";
}
},
toggleSeen: function() {
app.seen = false
app.button.push({ text: 'Show' });
}
}
})


</script>

出乎意料的是,按钮在隐藏和显示状态下都是空白的。作为 vue 的新手,这似乎是一种奇怪的方式。在这种情况下更改数据是不好的做法吗?我不明白如何解决这个问题,因为我的控制台没有错误。

最佳答案

这里有一个代码片段。

我通过一个普通对象而不是一个数组更改了您的按钮,并在方法 toggleSeen 中做了一些小改动。

// components
Vue.component('todoitem', {
template: "<li>Test Item</li>"
})

// app code
var app = new Vue({
el: '#app',
data: {
todos: [
{ text: 'Sample Item 1' },
{ text: 'Sample Item 2' },
{ text: 'Sample Item 3' }
],
button: {
text: 'Hide'
},
seen: true
},
methods: {
addItem: function() {
let item = document.getElementById("list-input").value;
let error = document.getElementById("error");
if (item == "") {
error.style.display = "block";
} else {
app.todos.push({ text: item });
error.style.display = "none";
}
},
toggleSeen: function() {
app.seen = !app.seen;
app.button.text = app.seen ? 'Hide' : 'Show';
}
}
});
<script src="https://vuejs.org/js/vue.min.js"></script>

<div id="app">
<ul>
<li v-for="todo in todos">
{{ todo.text }}
</li>
</ul>

<input type="text" id="list-input">
<input type="submit" id="list-submit" v-on:click="addItem">
<span id="error" style="color: red; display: none;">Please Enter Text</span>

<ul>
<todoitem></todoitem>
<todoitem></todoitem>
<todoitem></todoitem>
</ul>

<h2 v-if="seen">SEEN</h2>
<button id="hide-seen" v-on:click="toggleSeen">{{ button.text }}</button>
</div>

关于javascript - vue.js - 在事件发生后更改按钮内的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46567323/

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