美文网首页
前端基础vue-计算属性和侦听器及过滤器

前端基础vue-计算属性和侦听器及过滤器

作者: 让你变好的过程从来都不会很舒服 | 来源:发表于2024-01-05 19:40 被阅读0次

    1、计算属性(computed)

    某些结果是基于之前数据实时计算出来的,我们可以利用计算属性。来完成

    <div id="app">
    <ul>
    <li>西游记:价格{{xyjPrice}},数量:
    <input type="number" v-model="xyjNum"></li>
    <li>水浒传:价格{{shzPrice}},数量:
    <input type="number" v-model="shzNum"></li>
    <li>总价:{{totalPrice}}</li>
    </ul>
    </div>
    <script src="../node_modules/vue/dist/vue.js"></script>
    <script type="text/javascript">
    let app = new Vue({
    el: "#app",
    data: {
    xyjPrice: 56.73,
    shzPrice: 47.98,
    xyjNum: 1,
    shzNum: 1
    },
    computed: {
    totalPrice(){
    return this.xyjPrice*this.xyjNum + this.shzPrice*th
    is.shzNum;
    }
    },
    })
    </script>
    

    2、侦听(watch)

    watch 可以让我们监控一个值的变化。从而做出相应的反应。

    <div id="app">
    <ul>
    <li>西游记:价格{{xyjPrice}},数量:
    <input type="number" v-model="xyjNum"></li>
    <li>水浒传:价格{{shzPrice}},数量:
    <input type="number" v-model="shzNum"></li>
    <li>总价:{{totalPrice}}</li>
    {{msg}}
    </ul>
    </div>
    <script src="../node_modules/vue/dist/vue.js"></script>
    <script type="text/javascript">
    let app = new Vue({
    el: "#app",
    data: {
    xyjPrice: 56.73,
    shzPrice: 47.98,
    xyjNum: 1,
    shzNum: 1,
    msg:""
    },
    computed: {
    totalPrice(){
    return this.xyjPrice*this.xyjNum + this.shzPrice*th
    is.shzNum;
    }
    },
    watch: {
    xyjNum(newVal, oldVal){
    if(newVal >= 3){
    this.msg = "西游记没有更多库存了";
    this.xyjNum = 3;
    }else{
    this.msg = "";
    }
    }
    }
    })
    </script>
    

    3、过滤器(filters)

    过滤器不改变真正的data,而只是改变渲染的结果,并返回过滤后的版本。在很多不同的
    情况下,过滤器都是有用的,比如尽可能保持 API 响应的干净,并在前端处理数据的格式。
    示例:展示用户列表性别显示男女

    <body>
    <div id="app">
    <table>
    <tr v-for="user in userList">
    <td>{{user.id}}</td>
    <td>{{user.name}}</td>
    <!-- 使用代码块实现,有代码侵入 -->
    <td>{{user.gender===1? "男":"女"}}</td>
    </tr>
    </table>
    </div>
    </body>
    <script src="../node_modules/vue/dist/vue.js"></script>
    <script>
    let app = new Vue({
    el: "#app",
    data: {
    userList: [
    { id: 1, name: 'jacky', gender: 1 },
    { id: 2, name: 'peter', gender: 0 }
    ]
    }
    });
    </script>
    

    相关文章

      网友评论

          本文标题:前端基础vue-计算属性和侦听器及过滤器

          本文链接:https://www.haomeiwen.com/subject/kqpindtx.html