提问
需求
有一个这样的数组结构 其实我没明白为啥他截图是评论回复的,但代码里写的question?方-_-#
需求是删掉子数组中的item
questions:[
{
name:"1测试问题",
answers:[
{name:"chenghaolan",content:"ddd",status:1},
{name:"haoshuai",content:"aaa",status:1},
]
},
{
name:"2测试问题",
answers:[
{name:"chenghaolan",content:"ddd",status:1},
{name:"zhentmshuai",content:"aaa",status:1},
]
}
]
分析
传统思路是拿到该dom节点循环时被data-*的index ,然后要做两步删除:
- 删除dom节点
- 删掉数组中对应的数据
然而!我们用了vue 还分析个屁啊!
文档类数组操作 写的明明白白了:
干!
1.第一种方案采用$remove
代码清单:
<ul>
<li v-for="question in questions">
<div>{{question.name}}</div>
<ul class="answers">
<li v-if="answer.status==1" v-for="answer in question.answers">{{answer.name}}
<a href="javascript:void(0)" v-on:click="deleteItem(question.answers,answer)">删除</a>
</li>
<ul>
</li>
</ul>
export default {
data(){
return {
questions:[
{
name:"1测试问题",
answers:[
{name:"chenghaolan",content:"ddd",status:1},
{name:"haoshuai",content:"aaa",status:1},
]
},
{
name:"2测试问题",
answers:[
{name:"chenghaolan",content:"ddd",status:1},
{name:"zhentmshuai",content:"aaa",status:1},
]
}
]
}
},
methods:{
deleteItem(questions,answer){
console.info(questions)
questions.$remove(answer);
// answer.status = 0;不好意思这是第二种方案
}
}
}
2.结合v-if
如果没给你$remove怎么办?也没给你封装什么pop()乱糟的,咋整?
代码清单还是上面那个 只不过把click入参改为answer,方法内置状态就好了
以上两种方案都满足数据驱动视图的需求,如果你硬要用index也能做……恶心点就是……就不写了~
放上效果~
15点46接警 17点07解决并完成记录~中间还走了200多米上了趟厕所
欢迎加群讨论vue的使用153925634