zoukankan      html  css  js  c++  java
  • Vue笔记(一):Some points in the beginning

    1. v-if / v-show

    v-if 会确保在切换过程中条件块内的事件监听器和子组件适当地被销毁和重建。另外,v-if 直到条件第一次为真时,才会开始渲染条件块。

    v-show 不管初始条件是什么,元素总是会被渲染,并且只是简单地基于 CSS 进行切换。

    • v-if 有更高的切换开销,如果在运行时条件不太可能改变,则使用 v-if 较好
    • v-show 有更高的初始渲染开销,如果需要非常频繁地切换,则使用 v-show 较好

    2. computed / methods

    • computed 可被缓存,只要依赖不变就不会重新调用。以下使用 computed 过滤数组。
    <li v-for="n in evenNum">{{n}}</li>
    
    new Vue({
        el: 'ul',
        data: {
            num: [1, 2, 3, 4, 5]
        },
        computed: {
            evenNum: function(){
                return this.num.filter(function(n){
                    return n % 2 == 0;
                });
            }
        }    
    });
    
    • methods 每次调用方法总是重新执行函数。以下使用 methods 过滤数组。
    <li v-for="n in even(num)">{{n}}</li>
    
    new Vue({
        el: 'ul',
        data: {
            num: [1, 2, 3, 4, 5]
        },
        methods: {
            even: function(num){
                return num.filter(function(n){
                    return n % 2 == 0;
                });
            }
        }
    });
    

    3. v-for

    • 迭代数组
    <ul id="exp-1">
        <li v-for="(item, index) in list">
            {{index}} - {{item.txt}}
        </li>
    </ul>
    
    new Vue({
        el: '#exp-1',
        data: {
            list: [
                {txt: 'first'},
                {txt: 'second'},
                {txt: 'third'}
            ]
        }
    });
    
    0 - first
    1 - second
    2 - third
    
    • 迭代对象:按 Object.keys() 遍历
    <ul id="exp-2">
        <li v-for="(value, key, index) in obj">
            {{ index }} - {{ key }} - {{value}}
        </li>
    </ul>
    
    new Vue({
        el: '#exp-2',
        data: {
            obj: [
                {txt: 'first'},
                {txt: 'second'},
                {txt: 'third'}
            ]
        }
    });
    
    0 - name - qm
    1 - age - 22
    

    4. 数组限制

    由于 JavaScript 的限制,Vue 不能检测以下变动的数组:

    • 利用索引直接设置一个项: vm.list[idx] = newValue;
    可用以下两种方法实现相同效果触发状态更新
    
    // 1. 全局set方法
    Vue.set(vm.list, idx, newValue)
    
    // 2. Array.prototype.splice
    vm.list.splice(idx, 1, newValue)
    
    • 直接修改数组长度: vm.list.length = newLen;
    vm.list.splice(newLen)
    
  • 相关阅读:
    asp.net+Sqlserver 通过存储过程读取数据
    文字半透明显示在图片上
    饼形统计图
    折线统计图
    柱状统计图
    关于phonegap
    codesmith的使用
    asp.net读取Access数据库。
    Tomcat7.0安装配置
    freemarker数字格式化
  • 原文地址:https://www.cnblogs.com/qimeng/p/7639899.html
Copyright © 2011-2022 走看看