<template>
??<div>
????<div>
??????<ul>
????????<li?v-for="(item,index)?in?list?":key="index"
????????????@click="choose(index)"
????????????:class="{active:index?==?current?&&?current?!=?''}"
????????>
??????????{{item}}
????????</li>
??????</ul>
??????<ul>
????????<li?v-for="(item,index)?in?targetList?"?:key="index">
??????????{{item}}
????????</li>
??????</ul>
????</div>
????<button?@click="add()"?type="button">add</button>
??</div>
</template>
<script>
????export?default?{
????????name:?'listDemo',
????????data?()?{
????????????return?{
????????????????list:[1,2,3,4,5,6,7,8,9],
??????????????current:'',
??????????????targetList:[]
????????????}
????????},
????????components:?{},
????????methods:?{
????????????choose(index){
????????????????this.current=index;
????????????????console.log(index)
??????????????
????????????},
??????????add(){
????????????????this.targetList.push(this.list[this.current]);
????????????????this.current='';
????????????console.log(?this.targetList)
??????????}
????????},
????}
</script>
<!--?Add?"scoped"?attribute?to?limit?CSS?to?this?component?only?-->
<style?scoped>
??div>div{
????display:?flex;
??}
??ul{
????flex:?1;
??}
li{
??border:?1px?solid?pink;
??margin-bottom:?20px;
??height:?40px;
??line-height:?40px;
??cursor:?pointer;
}
??li.active{
????background:?greenyellow;
??}
</style>
2019-05-20
?回答里面的同學(xué)跟你解釋的很清楚啦!
主要原因就是if中的邏輯判斷寫的有問題。
:class="{active: index === current}"
這里使用強(qiáng)等,就可以了。
2019-07-13
在剛進(jìn)去頁面時候,未點(diǎn)擊時候,index是0嗎?
2019-05-19
用undefined的吧
2019-05-19
可以參考我的
<template>
? <div>
? ? <ul>
? ? ? <li
? ? ? ? v-for="(item, index) in list"
? ? ? ? :key="index"
? ? ? ? :class="{active: index === current}"
? ? ? ? @click="tap(index)"
? ? ? >
? ? ? ? {{ item }}
? ? ? </li>
? ? </ul>
? ? <button @click="add">添加</button>
? ? <ul>
? ? ? <li
? ? ? ? v-for="(item, index) in target"
? ? ? ? :key="index"
? ? ? >
? ? ? ? {{ item }}
? ? ? </li>
? ? </ul>
? </div>
</template>
<script>
export default {
? name: 'test',
? data () {
? ? return {
? ? ? current: undefined,
? ? ? list: [1, 2, 3, 4, 5, 6],
? ? ? target: []
? ? }
? },
? methods: {
? ? tap (index) {
? ? ? this.current = index
? ? ? console.log(index);
? ? },
? ? add () {
? ? ? if (this.current) {
? ? ? ? const item = this.list[this.current]
? ? ? ? this.target.push(item)
? ? ? ? this.current = undefined
? ? ? }
? ? }
? }
}
</script>
<style scoped>
li.active {
? background-color: green
? /* 不可以賦值為 'green' */
}
</style>
2019-05-19
就是第0個元素,判斷?0 != '' 時,為false,所以沒有應(yīng)用到這個樣式。所以老師這種寫法有問題
2019-05-19
choose(index){
? ? this.current=index;
? ? console.log(index)
? ? console.log(index == this.current); // true
? ? console.log(this.current != ''); // false
? ? console.log(index == this.current && this.current != ''); // false
? ? // 打印日志可知,當(dāng)點(diǎn)擊第一個元素時, 條件判斷為false
? ? // 即 0 != '' 這個表達(dá)式為false,所以 active: true
? ? // 這樣該元素就不能使用 active 這個樣式了
},