“Vue进阶:深入理解插值、指令、过滤器、计算属性和监听器“

简介: “Vue进阶:深入理解插值、指令、过滤器、计算属性和监听器“

引言:

Vue.js是一款流行的JavaScript框架,它提供了许多强大的功能来简化前端开发。在本篇博客中,我们将深入探讨Vue的一些高级特性,包括插值、指令、过滤器、计算属性和监听器。通过理解和灵活运用这些功能,我们可以更好地构建出丰富、高效的Vue应用程序。

Vue的插值

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.10/vue.js"></script>
    <title></title>
    <style>
      .font-30{
        font-size: 30px;
      }
    </style>
  </head>
  <body>
    <div id = "app">
      {{msg}}<br /><hr />
      html,class绑定-------<b :class="msg3" v-html="msg2"></b><br /><hr />
      表达式----<br />
      {{num+1}}<br />
      {{str.substring(2,4)}}<br />
      <input v-model="ok" />
      {{ok==true?'yes':'no'}}<br /><hr />
    </div>
    <script>
      new Vue({
        el:"#app",
        data(){
          return{
            msg:'hello vue',
            msg2:'<span style="color:red">msg2样式</span>',
            msg3:'font-30',
            num:6,
            str:'沉谭秋叶',
            ok:true
          }
        }
      })
    </script>
  </body>
</html>
• 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
• 29
• 30
• 31
• 32
• 33
• 34
• 35
• 36
• 37
• 38
• 39

Vue的指令

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.10/vue.js"></script>
    <title></title>
    <style>
      .font-30{
        font-size: 30px;
      }
    </style>
  </head>
  <body>
    <div id = "app">
      <input v-model="score" />
      <b v-if="score < 60">不合格</b>
      <b v-else-if="score >= 60 && score < 70">及格</b>
      <b v-else-if="score >= 70 && score < 80">一般</b>
      <b v-else-if="score >= 80 && score < 90">良好</b>
      <b v-else>优秀</b>
      <br /><hr />
      v-show
      <b v-show="isShow">xxx</b>
      <br /><hr />
      v-for
      <b v-for="i in arr">{{i}}-</b>
      <b v-for="i in arrs">{{i.name}}-{{i}}=</b>  <br /><hr />
      <select>
        <option>请选择</option>
        <option v-for="i in arrs" :value="i.id">{{i.name}}</option>
      </select>
      <br /><hr />
      <div v-for="i in arrs"> 
        <input type="checkbox" name="hobby" :value="i.id" />{{i.name}}
      </div>
      <br /><hr />
      <input v-model="evename"/>
      <button v-on:[evename]="text">点击</button>
    </div>
    <script>
      new Vue({
        el:"#app",
        data(){
          return{
            score:69,
            isShow:false,
            arr:['a','b','c','d'],
            arrs:[{name:'小王',id:1},{name:'小李',id:2},{name:'小桂',id:3},{name:'小勇',id:4}],
            evename:'click'
          }
        },methods:{
          text(){
            alert('点击了!!')
          }
        }
      })
    </script>
  </body>
</html>
• 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
• 29
• 30
• 31
• 32
• 33
• 34
• 35
• 36
• 37
• 38
• 39
• 40
• 41
• 42
• 43
• 44
• 45
• 46
• 47
• 48
• 49
• 50
• 51
• 52
• 53
• 54
• 55
• 56
• 57
• 58
• 59

Vue的过滤器

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <script src="jquery.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.10/vue.js"></script>
    <script src="date.js"></script>
    <title></title>
  </head>
  <body>
    <div id = "app">
      {{msg}}<br>
      {{msg | filter1}} <br>
      {{msg | filter1 | filter2}}<br>
      {{msg | filter3(3,7)}}<br>
      <hr>
      {{time}}<br>
      {{time | filterName}}
    </div>
    <script>
      Vue.filter('filterName', function (value) {
       // value 表示要过滤的内容
       return fmtDate(value);
      });
      new Vue({
        el:"#app",
        filters:{
          'filter1':function(v){
            return v.substring(0,5)
          },
          'filter2':function(v){
            return v.substring(1,3)
          },
          'filter3':function(v,begin,end){
            return v.substring(begin,end)
          }
        },
        data(){
          return{
            msg:'允许你自定义过滤器,被用作一些常见的文本格式化,格式如下',
            time:new Date()
          }
        }
      })
    </script>
  </body>
</html>
• 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
• 29
• 30
• 31
• 32
• 33
• 34
• 35
• 36
• 37
• 38
• 39
• 40
• 41
• 42
• 43
• 44
• 45
• 46
• 47
• 48
• 49

Vue的计算属性和监听器

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.10/vue.js"></script>
    <title></title>
    <style>
      .font-30{
        font-size: 30px;
      }
    </style>
  </head>
  <body>
    <div id = "app">
      {{msg}}<br /><hr />
      单价<input v-model="price"/>
      数量<input v-model="num"/>
      小计{{count}}
      <br />
      千米<input v-model="km"/><br />
      米<input v-model="m"/>
    </div>
    <script>
      new Vue({
        el:"#app",
        data(){
          return{
            msg:'hello vue',
            price:88,
            num:1,
            m:1000,
            km:1
          }
        },computed:{
          count:function(){
            return this.price*this.num
          }
        },watch:{
          km:function(v){
             this.m = parseInt(v)*1000;
          },
          m:function(v){
             this.km = parseInt(v)/1000;
          }
        }
      })
    </script>
  </body>
</html>
• 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
• 29
• 30
• 31
• 32
• 33
• 34
• 35
• 36
• 37
• 38
• 39
• 40
• 41
• 42
• 43
• 44
• 45
• 46
• 47
• 48
• 49

data.js

//给Date类添加了一个新的实例方法format
Date.prototype.format = function (fmt) {
  //debugger;
    var o = {
        "M+": this.getMonth() + 1,                 //月份
        "d+": this.getDate(),                    //日
        "h+": this.getHours(),                   //小时
        "m+": this.getMinutes(),                 //分
        "s+": this.getSeconds(),                 //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};
function fmtDate(date, pattern) {
  var ts = date.getTime();
    var d = new Date(ts).format("yyyy-MM-dd hh:mm:ss");
    if (pattern) {
        d = new Date(ts).format(pattern);
    }
    return d.toLocaleString();
};
• 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
• 29

vue购物车案例

<!DOCTYPE html>
<html>
<head>
  <title>购物车</title>
  <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.10/vue.js"></script>
  <style>
    table {
      border-collapse: collapse;
      width: 100%;
    }
    th, td {
      border: 1px solid black;
      padding: 8px;
      text-align: left;
    }
    th {
      background-color: #f2f2f2;
    }
    .btn-group {
      display: flex;
      justify-content: space-between;
    }
  </style>
</head>
<body>
  <div id="app">
    <h1>购物车</h1>
    <table>
      <thead>
        <tr>
          <th>商品</th>
          <th>价格</th>
          <th>数量</th>
          <th>小计</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="v in arr" >
          <td>{{ v.name }}</td>
          <td>{{ v.price }}</td>
          <td>
            <input type="number" v-model="v.quantity" @input="xj(v)">
          </td>
          <td>{{ v | filter1 }}</td>
          <td class="btn-group">
            <button @click="add(v)">+</button>
            <button @click="jdd(v)">-</button>
          </td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <td colspan="3">总计</td>
          <td>{{ total }}</td>
        </tr>
      </tfoot>
    </table>
  </div>
  <script>
    new Vue({
      el: '#app',
      data: {
        arr: [
          { name: '尿不湿', price: 49, quantity: 1, subtotal: 49 },
          { name: '狼牙棒', price: 28, quantity: 1, subtotal: 28 },
          { name: '鸡毛卷', price: 36, quantity: 1, subtotal: 36 }
        ]
      },
      computed: {
        total: function() {
          return this.arr.reduce((sum, v) => sum + v.subtotal, 0);
        }
      },
      methods: {
        xj: function(v) {
          v.subtotal = v.price * v.quantity;
        },
        add: function(v) {
          v.quantity++;
          this.xj(v);
        },
        jdd: function(v) {
          if (v.quantity > 0) {
            v.quantity--;
            this.xj(v);
          }
        }
      },
      filters: {
        'filter1': function(v) {
          return v.price * v.quantity;
        }
      }
    });
  </script>
</body>
</html>
• 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
• 29
• 30
• 31
• 32
• 33
• 34
• 35
• 36
• 37
• 38
• 39
• 40
• 41
• 42
• 43
• 44
• 45
• 46
• 47
• 48
• 49
• 50
• 51
• 52
• 53
• 54
• 55
• 56
• 57
• 58
• 59
• 60
• 61
• 62
• 63
• 64
• 65
• 66
• 67
• 68
• 69
• 70
• 71
• 72
• 73
• 74
• 75
• 76
• 77
• 78
• 79
• 80
• 81
• 82
• 83
• 84
• 85
• 86
• 87
• 88
• 89
• 90
• 91
• 92
• 93
• 94
• 95
• 96
• 97
• 98
• 99
• 100
• 101
• 102
• 103

总结:

通过本篇博客的学习,我们深入理解了Vue的插值、指令、过滤器、计算属性和监听器这些高级特性。这些功能不仅可以帮助我们更好地处理数据绑定和DOM操作,还能提升应用程序的性能和开发效率。在实际项目中,我们应根据具体需求合理运用这些功能,以构建出饱满、高效的Vue应用程序。


相关文章
|
6月前
|
JavaScript
Vue中如何实现兄弟组件之间的通信
在Vue中,兄弟组件可通过父组件中转、事件总线、Vuex/Pinia或provide/inject实现通信。小型项目推荐父组件中转或事件总线,大型项目建议使用Pinia等状态管理工具,确保数据流清晰可控,避免内存泄漏。
562 2
|
5月前
|
缓存 JavaScript
vue中的keep-alive问题(2)
vue中的keep-alive问题(2)
463 137
|
9月前
|
人工智能 JavaScript 算法
Vue 中 key 属性的深入解析:改变 key 导致组件销毁与重建
Vue 中 key 属性的深入解析:改变 key 导致组件销毁与重建
1013 0
|
9月前
|
JavaScript UED
用组件懒加载优化Vue应用性能
用组件懒加载优化Vue应用性能
|
8月前
|
人工智能 JSON JavaScript
VTJ.PRO 首发 MasterGo 设计智能识别引擎,秒级生成 Vue 代码
VTJ.PRO发布「AI MasterGo设计稿识别引擎」,成为全球首个支持解析MasterGo原生JSON文件并自动生成Vue组件的AI工具。通过双引擎架构,实现设计到代码全流程自动化,效率提升300%,助力企业降本增效,引领“设计即生产”新时代。
602 1
|
9月前
|
JavaScript 前端开发 开发者
Vue 自定义进度条组件封装及使用方法详解
这是一篇关于自定义进度条组件的使用指南和开发文档。文章详细介绍了如何在Vue项目中引入、注册并使用该组件,包括基础与高级示例。组件支持分段配置(如颜色、文本)、动画效果及超出进度提示等功能。同时提供了完整的代码实现,支持全局注册,并提出了优化建议,如主题支持、响应式设计等,帮助开发者更灵活地集成和定制进度条组件。资源链接已提供,适合前端开发者参考学习。
616 17
|
8月前
|
JavaScript 安全
在 Vue 中,如何在回调函数中正确使用 this?
在 Vue 中,如何在回调函数中正确使用 this?
415 0
|
9月前
|
JavaScript 前端开发 UED
Vue 表情包输入组件实现代码及详细开发流程解析
这是一篇关于 Vue 表情包输入组件的使用方法与封装指南的文章。通过安装依赖、全局注册和局部使用,可以快速集成表情包功能到 Vue 项目中。文章还详细介绍了组件的封装实现、高级配置(如自定义表情列表、主题定制、动画效果和懒加载)以及完整集成示例。开发者可根据需求扩展功能,例如 GIF 搜索或自定义表情上传,提升用户体验。资源链接提供进一步学习材料。
545 1
|
9月前
|
存储 JavaScript 前端开发
如何高效实现 vue 文件批量下载及相关操作技巧
在Vue项目中,实现文件批量下载是常见需求。例如文档管理系统或图片库应用中,用户可能需要一次性下载多个文件。本文介绍了三种技术方案:1) 使用`file-saver`和`jszip`插件在前端打包文件为ZIP并下载;2) 借助后端接口完成文件压缩与传输;3) 使用`StreamSaver`解决大文件下载问题。同时,通过在线教育平台的实例详细说明了前后端的具体实现步骤,帮助开发者根据项目需求选择合适方案。
873 0
|
9月前
|
JavaScript 前端开发 UED
Vue 项目中如何自定义实用的进度条组件
本文介绍了如何使用Vue.js创建一个灵活多样的自定义进度条组件。该组件可接受进度段数据数组作为输入,动态渲染进度段,支持动画效果和内容展示。当进度超出总长时,超出部分将以红色填充。文章详细描述了组件的设计目标、实现步骤(包括props定义、宽度计算、模板渲染、动画处理及超出部分的显示),并提供了使用示例。通过此组件,开发者可根据项目需求灵活展示进度情况,优化用户体验。资源地址:[https://pan.quark.cn/s/35324205c62b](https://pan.quark.cn/s/35324205c62b)。
445 0