vue计算属性computed与过滤器filter

computed

  • 使用计算属性的方法和使用状态是一样的
  • 优点(特点): 逻辑计算, 防止模板过重, 有缓存(就是在同一个页面使用多次时, 只需计算一次)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>计算属性</title>
    <!-- 导入本地的vue     -->
    <script src="./vue.js"></script>
</head>
<body>
    <div id="Box">
        <div> 状 态: {
   
   { name }}</div>
        <div>计算属性: {
   
   { computedName }} </div>
    </div>
    <script>
        var box = new Vue({
     
     
            el: "#Box",
            data: {
     
     
                name: 'lanxiaobai'
            },
            // computed 定义计算属性
            computed: {
     
     
                computedName () {
     
     
                    // 把状态 name 的值首字母大写
                    return this.name.substring(0,1).toUpperCase() + this.name.substring(1)
                }
            }
        })
    </script>
</body>
</html>

filter

  • 过滤器
  • 使用方法 { { 数据 | 过滤器 }}
  • 对数据进行处理
  • 当对一个数据的格式不满意, 可在filter中进行过滤
<!--
File: demo32_过滤器.html
Created Date: 2021-01-03 14:32:59
Author: 蓝小白
Contact: <[email protected]>
Last Modified: Wednesday February 3rd 2021 10:55:18 am
-->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>vue过滤器</title>
    <!-- 导入本地的vue     -->
    <script src="./vue.js"></script>
</head>
<body>
    <div id="app">
        <div> 字符串 原始 值: {
   
   { 'lanxiaobai' }} </div>
        <div> 使用一个过滤器: {
   
   { 'lanxiaobai' | uppercase }} </div>
        <div> 使用两个过滤器: {
   
   { 'lanxiaobai' | uppercase | sub}} </div>
        <!--过滤器可以串联使用, 使用Vue.filter定义-->
    </div>
    <script>
        // 自定义的过滤器 uppercase, toUpperCase会把字母大写
        Vue.filter("uppercase",function(str){
     
     
            return str.toUpperCase()
        })
        // 自定义过滤器sub, 提取字符串的前两个字符
        Vue.filter("sub",function(str){
     
     
            return str.substring(0,2)
        })
        var app = new Vue({
     
     
            el:"#app",
        })
    </script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/lxb_wyf/article/details/111318888