美好的一天,如何從反向方法中洗掉陣列?
這是我的代碼
const app = Vue.createApp({
data() {
return {
app_title: 'Simple Checklist App',
entered_task_value: '',
list_of_tasks: [],
is_priority: false,
}
},
computed: {
reverseItems() {
return [...this.list_of_tasks].reverse();
}
},
methods: {
add_item() {
this.list_of_tasks.push(
{
id: this.list_of_tasks.length 1,
data: this.entered_task_value,
priority: this.is_priority,
}
);
this.entered_task_value = '';
this.is_priority = '';
},
total_tasks() {
return this.list_of_tasks.length;
},
remove_item(task_index) {
return this.reverseItems.splice(task_index, 1);
}
},
});
app.mount('#app');
該remove_item方法不起作用,我不確定如何正確呼叫內部的屬性computed
remove_item(task_index) {
return this.reverseItems.splice(task_index, 1);
}
這是 HTML
<ul>
<li
v-for="(task, task_index) in reverseItems"
class="item"
:key="task.id"
:class="{priority: task.priority}"
>
{{task.id}}
{{task.data}}
<button v-on:click="remove_item(task_index)">Remove</button>
</li>
</ul>
先感謝您!
uj5u.com熱心網友回復:
您應該更新任務陣列的 list_of_tasks 而不是computed陣列。
計算值是根據實際資料計算的,并在每次資料更改時更新。
這是關于 vue.js 中計算屬性的檔案
這是一個小例子
new Vue({
el: '#app',
data: () => {
return {
myArr: [1,2,3,4,5]
}
},
computed: {
myArrReversed(){
return [...this.myArr].reverse()
}
},
methods : {
addItem(){
this.myArr.push(this.myArr.length 1)
},
removeItem(){
this.myArr.splice(this.myArr.length - 1, 1)
},
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<ul>
<li v-for="item of myArrReversed" :key='item'>
{{item }}
</li>
</ul>
<button @click="addItem">Add item</button>
<button @click="removeItem">Remove item</button>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/473075.html
標籤:javascript Vue.js
