vue中v-for和v-if一起使用之使用compute的示例代码

目录
  • 版本
  • 目标效果
  • 说明
  • 解决方法
  • 核心代码片段
  • Car.vue

版本

vue 2.9.6
element-ui: 2.15.6

目标效果

说明

在 vue 2.x 中,在一个元素上同时使用 v-if 和 v-for 时,v-for 会优先作用

解决方法

选择性地渲染列表,例如根据某个特定属性(category )来决定不同展示渲染,使用计算属性computed使用template占位,将循环放在template中,v-if作用于元素,此方法script中不用定义computed方法,见 https://www.jb51.net/article/247179.htm

核心代码片段

# html
...
<el-divider content-position="left">奥迪</el-divider>
<el-link type="primary" target="_blank" v-for="(item, index) in links0" :key="index" :href="item.url" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >
  <el-button type="primary">{{item.name}}</el-button>
</el-link>
...
# script
...
computed: {
  links0: function() {
    return this.links.filter((item) => {
      return item.category === 0
    })
  },
  links1: function() {
    return this.links.filter((item) => {
      return item.category === 1
    })
  },
  links2: function() {
    return this.links.filter((item) => {
      return item.category === 2
    })
  }
},

Car.vue

<template>
  <div>
    <el-row>
      <el-col :span="24">
        <el-form :inline="true" class="user-search">
          <el-form-item>
            <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEdit()" plain>添加链接</el-button>
          </el-form-item>
        </el-form>
        <div >
          <el-divider content-position="left">奥迪</el-divider>
          <el-link type="primary" target="_blank" v-for="(item, index) in links0" :key="index" :href="item.url" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >
            <el-button type="primary">{{item.name}}</el-button>
          </el-link>
          <el-divider content-position="left">奔驰</el-divider>
          <el-link type="primary" target="_blank" v-for="(item, index) in links1" :key="index" :href="item.url" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >
            <el-button type="primary">{{item.name}}</el-button>
          </el-link>
          <el-divider content-position="left">宝马</el-divider>
          <el-link type="primary" target="_blank" v-for="(item, index) in links2" :key="index" :href="item.url" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >
            <el-button type="primary">{{item.name}}</el-button>
          </el-link>
        </div>
        <!-- 添加界面 -->
        <el-dialog :title="title" :visible.sync="editFormVisible" width="30%" @click="closeDialog">
          <el-form label-width="120px" :model="editForm" :rules="rules" ref="editForm">
          <el-form-item label="链接名称" prop="name">
            <el-input size="small" v-model="editForm.name" auto-complete="off" placeholder="请输入链接名称"></el-input>
          </el-form-item>
          <el-form-item label="链接地址" prop="url">
            <el-input size="small" v-model="editForm.url" auto-complete="off" placeholder="请输入链接地址"></el-input>
          </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="closeDialog">取消</el-button>
          <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm('editForm')">保存</el-button>
          </div>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { getLink, saveLink } from '../../api/userMG'
export default {
  data() {
    return {
      links: [],
      loading: false, //显示加载
      editFormVisible: false, //控制添加页面显示与隐藏
      title: '添加链接',
      editForm: {
        name: '',
        url: ''
      },
      // rules表单验证
      rules: {
        name: [{ required: true, message: '请输入链接名称', trigger: 'blur' }],
        url: [{ required: true, message: '请输入链接地址', trigger: 'blur' }]
      },
    }
  },
  computed: {
    // 通过根据category属性来不同显示
    links0: function() {
      return this.links.filter((item) => {
        return item.category === 0
      })
    },
    links1: function() {
      return this.links.filter((item) => {
        return item.category === 1
      })
    },
    links2: function() {
      return this.links.filter((item) => {
        return item.category === 2
      })
    }
  },
  created() {
    // 获取链接
   this.getdata()
  },
  // 这下面的方法只有被调用才会被执行
  methods: {
    // 获取链接
    getdata() {
      this.loading = true
      getLink().then((response) => {
        this.loading = false
        console.log(response.data)
        this.links = response.data
      }).catch(error => {
        console.log(error)
      })
    },
    // 添加页面方法
    handleEdit: function() {
      this.editFormVisible = true
      this.title = '添加链接',
      this.editForm.name = '',
      this.editForm.url = ''
    },
    // 添加保存页面方法
    submitForm(editData) {
      this.$refs[editData].validate(valid => {
        if (valid) {
          saveLink(this.editForm).then(response => {
            this.editFormVisible = false
            this.loading = false
            // if (response.success)
            this.getdata()
            this.$message({
              type: 'success',
              message: '链接添加成功'
            })
          }).catch(error => {
            this.editFormVisible = false
            this.loading = false
            // console.log(error.response.data['url'][0])
            // console.log(error.response.status)
            // this.$message.error('链接添加失败,请稍后再试')
            if (error.response.status == 400 ) {
              this.$message.error(error.response.data['url'][0]+'如: http://xxx 或 https://xxx')
            }else {
              this.$message.error('链接添加失败,请稍后再试')
            }
          })
        }
      })
    },
    // 关闭添加链接窗口
    closeDialog() {
      this.editFormVisible = false
    }
  }
}
</script>
<style>
  /* .el-row {
    margin-top: 10px;
  } */
  .el-link {
    margin-right: 5px;
  }
</style>

到此这篇关于vue中v-for和v-if一起使用之使用compute的文章就介绍到这了,更多相关vue v-for和v-if一起使用内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • 详解vue中v-for和v-if一起使用的替代方法template

    目录 版本 目标效果 说明 解决方法 核心代码片段 Car.vue vue中v-for和v-if一起使用的替代方法template 版本 vue 2.9.6element-ui: 2.15.6 目标效果 说明 在 vue 2.x 中,在一个元素上同时使用 v-if 和 v-for 时,v-for 会优先作用 解决方法 选择性地渲染列表,例如根据某个特定属性(category )来决定不同展示渲染,使用计算属性computed 见https://www.jb51.net/article/24717

  • vue的注意规范之v-if 与 v-for 一起使用教程

    当 v-if 与 v-for 一起使用时,v-for 具有比 v-if 更高的优先级,这意味着 v-if 将分别重复运行于每个 v-for 循环中 所以,不推荐v-if和v-for同时使用 使用推荐方式: <ul> <li v-for="user in activeUsers" :key="user.id" > {{ user.name }} </li> </ul> <ul v-if="shouldSh

  • Vue中的computed属性详解

    目录 插值表达式 methods computed 总结 今天来说说vue中的计算属性computed,为了更好的理解计算属性的好处,我们先通过一个案例来慢慢 了解计算属性,有如下案例:定义两个输入框以及一个span标签,span标签中的内容为两个输入框中的值,span标签中的内容随着输入框中的内容变化而变化 插值表达式 我们先用插值表达式的方法来实现这一效果 <body> <div id="app"> 姓: <input type="text&

  • vue中v-for和v-if一起使用之使用compute的示例代码

    目录 版本 目标效果 说明 解决方法 核心代码片段 Car.vue 版本 vue 2.9.6element-ui: 2.15.6 目标效果 说明 在 vue 2.x 中,在一个元素上同时使用 v-if 和 v-for 时,v-for 会优先作用 解决方法 选择性地渲染列表,例如根据某个特定属性(category )来决定不同展示渲染,使用计算属性computed使用template占位,将循环放在template中,v-if作用于元素,此方法script中不用定义computed方法,见 htt

  • Vue.js常用指令汇总(v-if、v-for等)

    有时候指令太多会造成记错.记混的问题,所以本文在记忆的时候会采用穿插记忆的方式,交叉比对,不易出错. 本文主要讲了一下六个指令: v-if//v-show//v-else//v-for//v-bind//v-on 1. v-if 条件渲染指令,根据其后表达式的bool值进行判断是否渲染该元素: eg: HTML: <div id="example01"> <p v-if="male">Male</p> <p v-if=&qu

  • 详解为什么Vue中的v-if和v-for不建议一起用

    本文主要介绍了为什么v-if和v-for不建议一起用?分享给大家,具体如下: 一.作用 v-if 指令用于条件性地渲染一块内容.这块内容只会在指令的表达式返回 true值的时候被渲染 v-for 指令基于一个数组来渲染一个列表.v-for 指令需要使用 item in items 形式的特殊语法,其中 items 是源数据数组或者对象,而 item 则是被迭代的数组元素的别名 在 v-for 的时候,建议设置key值,并且保证每个key值是独一无二的,这便于diff算法进行优化 两者在用法上 <

  • vue2和vue3的v-if与v-for优先级对比学习

    Vue.js 中使用最多的两个指令就是 v-if 和 v-for ,因此我们可能会想要同时使用它们.虽然官方不建议这样做,但有时确实是必须的,我们来了解下他们的工作方式: 在 vue 2.x 中,在一个元素上同时使用 v-if 和 v-for 时, v-for 会优先作用. 在 vue 3.x 中, v-if 总是优先于 v-for 生效. 对比学习 接下来我们通过一个简单的示例来感知下,假设我们想要实现一个极简的 todoList 效果: 我们有一个 todoList: const todoL

  • BootStrap中的模态框(modal,弹出层)功能示例代码

    bootstrap中的模态框(modal),不同于Tooltips,模态框以弹出对话框的形式出现,具有最小和最实用的功能集.务必将模态框的 HTML 代码放在文档的最高层级内(也就是说,尽量作为 body 标签的直接子元素),以避免其他组件影响模态框的展现或功能. 默认的modal示例: <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8">

  • Vue中通过属性绑定为元素绑定style行内样式的实例代码

    1.直接在元素上通过:style的形式,书写样式对象 <h1 :style="{color:'red','font-weight':200}">这是一个H1</h1> 2.将样式对象定义在data中,并直接引用到:style中 1:在data上定义样式 data:{ styleObj1:{color:'blue','font-weight':200,'font-size':'40px'}, } 2:在元素中,通过属性绑定的形式,将样式对象应用到元素中 <h

  • 浅谈 vue 中的 watcher

    观察 Watchers 虽然计算属性在大多数情况下更合适,但有时也需要一个自定义的 watcher .这是为什么 Vue 提供一个更通用的方法通过watch 选项,来响应数据的变化.当你想要在数据变化响应时,执行异步操作或开销较大的操作,这是很有用的. 大家对于 watch 应该不陌生,项目中都用过下面这种写法: watch: { someProp () { // do something } } // 或者 watch: { someProp: { deep: true, handler ()

  • 关于Vue中axios的封装实例详解

    前言 axios 是 Vue 官方推荐的一个 HTTP 库,用 axios 官方简介来介绍它,就是: Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中. 作为一个优秀的 HTTP 库,axios 打败了曾经由 Vue 官方团队维护的 vue-resource,获得了 Vue 作者尤小右的大力推荐,成为了 Vue 项目中 HTTP 库的最佳选择. 虽然,axios 是个优秀的 HTTP 库,但是,直接在项目中使用并不是那么方便,所以,我们需要对其进行一

  • vue中data的基础汇总

    目录 vue中如何重置data 组件中的data为什么是一个函数 为什么new Vue里的data可以是一个对象 vue中如何重置data 重置data需要了解3个小知识点 (1)this.$data获取组件当前状态的data对象 (2)this.$options.data获取组件初始状态的data对象 (3)Object.assign()方法用于将所有可美剧属性的值从一个或者多个源对象复制到目标对象,并返回目标对象. Object.assign(target,source1,source2,.

  • vue 开发一个按钮组件的示例代码

    最近面试,被问到一个题目,vue做一个按钮组件: 当时只是说了一下思路,回来就附上代码. 解决思路: 通过父子组件通讯($refs 和 props) props接受参数, $refs调用子组件的方法 来达到点击提交改变按钮状态,如果不成功则取消按钮状态 在src/components/ 下建一个button.vue <template> <!-- use plane --> <!-- 传入bgColor改变按钮背景色 --> <!-- state切换button的

  • Vue快速实现通用表单验证的示例代码

    本文开篇第一句话,想引用鲁迅先生<祝福>里的一句话,那便是:"我真傻,真的,我单单知道后端整天都是CRUD,我没想到前端整天都是Form表单".这句话要从哪里说起呢?大概要从最近半个月的"全栈工程师"说起.项目上需要做一个城市配载的功能,顾名思义,就是通过框选和拖拽的方式在地图上完成配载.博主选择了前后端分离的方式,在这个过程中发现:首先,只要有依赖jQuery的组件,譬如Kendoui,即使使用了Vue,依然需要通过jQuery去操作DOM.其次,只有

  • Mybatis 中的一对一,一对多,多对多的配置原则示例代码

    什么是 MyBatis ? MyBatis 是支持定制化 SQL.存储过程以及高级映射的优秀的持久层框架.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.MyBatis 可以对配置和原生Map使用简单的 XML 或注解,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录. 表:market_plan(营销计划(关联了用户)) market_plan_product(产品关联营销计划) mark

  • 八个Vue中常用的v指令详解

    目录 Vue中常用的8种v指令 1 v-text 指令 2 v-html 指令 3 v-on 指令 案例:计数器 4 v-show 指令 5 v-if 指令 6 v-bind 指令 7 v-for 指令 8 v-on 补充 总结 Vue中常用的8种v指令 根据官网的介绍,指令 是带有 v- 前缀的特殊属性.通过指令来操作DOM元素 指令 功能 v-text=“变量/表达式” 文本的设置字符串变量+数字可以直接写是拼接字符串如果出现要使用外部不相同的引号 v-html=“变量” 文本或者页面的设置

随机推荐