 
		qq_大小姐_7
2019-05-18 14:01
<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> 
				?回答里面的同学跟你解释的很清楚啦!
主要原因就是if中的逻辑判断写的有问题。
:class="{active: index === current}"
这里使用强等,就可以了。
 
				在刚进去页面时候,未点击时候,index是0吗?
 
				
用undefined的吧
 
				可以参考我的
<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>
 
				就是第0个元素,判断 0 != '' 时,为false,所以没有应用到这个样式。所以老师这种写法有问题
 
				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
// 打印日志可知,当点击第一个元素时, 条件判断为false
// 即 0 != '' 这个表达式为false,所以 active: true
// 这样该元素就不能使用 active 这个样式了
},
3小时速成 Vue2.x 核心技术
82564 学习 · 499 问题
相似问题