随笔 - 419  文章 - 3  评论 - 331  阅读 - 120万

Vue 简单实例 地址选配8 - 确认地址 - 设为默认地址

我们可以看到所有的地址都是点亮的状态,就是外面都有个橙色的框。我们需要把默认地址,才设置为点亮的状态。

1、新建变量 checkedIndex,默认为 0,然后把遍历地址列表,把字段 isDefault 为 true 的地址索引赋值给 checkedIndex

复制代码
data() {
    return {
      checkedIndex: 0, // 默认选中的索引
    }
},
methods: {
    getAddress() {
      this.axios.get('/mock/address.json').then(res => {
        console.log(res)
        this.addrList = res.data.data
        this.addrList.forEach((item, index) => {
          if (item.isDefault) {
            this.checkedIndex = index
          }
        })
      })
    },
}
复制代码

2、修改循环代码:

<li :class="{ check: item.isDefault }" v-for="item in addrFilter" :key="item.addressId">

也可以写为:

<li  :class="{ check: checkedIndex == index }" v-for="(item, index) in addrFilter" :key="item.addressId">

此时效果图:

3、添加点击事件:

<li :class="{ check: checkedIndex == index }"
     v-for="(item, index) in addrFilter" :key="item.addressId"
     @click="checkedIndex = index">

把当前索引赋值给 checkedIndex。

点击第一个地址后的效果图:

4、给设为默认添加点击事件:

复制代码
<a href="javascript:;" class="addr-set-default-btn" @click="slectDefault(index)">
       <i>设为默认</i>
</a>

<script>
export default {
  methods: {
    // 设为默认
    slectDefault(index) {
      console.log(index)
      this.addrList.map((item, i) => {
        if (index == i) {
          item.isDefault = true
        } else {
          item.isDefault = false
        }
      })
    }
  }
}
</script>
复制代码

当前点击的索引和遍历中的索引一致时,设为 true ,其他都设置为 false。

也可以点击时传递 addressId,效果都是一样的:

复制代码
<a href="javascript:;" class="addr-set-default-btn" @click="slectDefault(item.addressId)">
       <i>设为默认</i>
</a>

<script>
export default {
  methods: {
    // 设为默认
    slectDefault(id) {
      console.log(id)
      this.addrList.map(item => {
        if (id == item.addressId) {
          item.isDefault = true
        } else {
          item.isDefault = false
        }
      })
    }
  }
}
</script>
复制代码

切换后的效果图:

 

posted on   JoeYoung  阅读(1015)  评论(0编辑  收藏  举报
编辑推荐:
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
阅读排行:
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
历史上的今天:
2009-04-27 主流互联网公司的产品项目流程
< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

点击右上角即可分享
微信分享提示