vue——示例1(实现ul点击文字变色,默认第一个li文字变色)

实例1

template

<ul>
      <li
        v-for="(item,index) in arr"
        :key="item.name"
        :class="{active:index === currentIndex}"
        @click="liClick(index)"
      >{{index+1}}.{{item.name}}</li>
    </ul>

js

export default {
  data() {
    return {
      arr: [
        {
          name: "shasha",
          age: 27,
        },
        {
          name: "he",
          age: 29,
        },
        {
          name: "hex",
          age: 2,
        },
      ],
      currentIndex: 0,
    };
  },
  methods: {
    liClick(index) {
      this.currentIndex = index;
    },
  },
};

style

<style scoped>
ul > li {
  cursor: pointer;
}
.active {
  color: red;
}
</style>

实例2

template

<template>
  <div>
    <h2>示例1</h2>
    <ul>
    //对象方式:class="{类名:布尔值}"
      <li v-for="(po,index) in posts" :key="po.id" :class="{active:po.active}"  @click="liClick(po,index)">{{po.title}}</li>
    </ul>
  </div>
</template>

js

data() {
    return {
      posts: [
        { id: 1, title: "My journey with Vue" ,active:false},
        { id: 2, title: "Blogging with Vue",active:false },
        { id: 3, title: "Why Vue is so fun" ,active:false},
      ],
    };
  },
   //渲染前
  create(){

  },
  //页面渲染后
  mounted() {
    this.posts[0].active = true;
  },
  methods:{
    liClick(e,i){
      this.posts.forEach((item,index)=>{
        if(index != i)
          item.active = false;
        else
          this.posts[i].active = true;
      })
    }
  }
};

style

<style scoped>
.active {
  color: red;
}
</style>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值