zoukankan      html  css  js  c++  java
  • Vue总结(三)

    Vue 实例还暴露了一些有用的实例属性与方法。它们都有前缀 $,以便与用户定义的属性区分开来。

     var App = new Vue({
           el: "#root",
           data: {
                message: "asdasdasd"
           }
    )};
    App.$weach("message",function(newVal,oldVal) {
        console.log(newVal);
        console.log(oldVal); 
    });
    //es6中的箭头函数中的this并不是实例,要使用是用实例,可使用实例的对象App.message = "assassin";
    

    模板语法

    {{}}差值表达式

    v-text="message" <=> {{}}
    
    message: "<h1>asjkfjaklsfj</h1>"
    
    <div v-html="message"></div>
    

    javascript表达式

    在差值里面可以书写JavaScript表达式

    {{message.split('').reverse().join('')}}
    //不能执行语句,都只能是单个的表达式。
    

    修饰符

    .prevent: 阻止默认事件
    .stop:组织时间冒泡

    过滤器

    var app = new Vue({
        el: "#root",
        template: `<div>{{message | upperCase | lowerCase}}</div>`,//message 后面 | 过滤函数,相应的过滤函数在filter对象中定义
        data: {
            message: "assassin"
        },
        filters: {
            upperCase: function(value) {
                return value.toUpperCase();
            },
            lowerCase: function(value) {
                return value.toLowerCase();
            }
        }
    });
    

    计算属性

    把我们的数据在的处理在输出

    var app = new Vue({
        el: "#root",
        template: `<div>{{reverseMsg}}</div>`,
        data: {
            message: "assassin"
        },//这这里不能使用methods
        computed: {//把我们的数据在的处理在输出
            reverseMsg: function(value) {
                return this.message.split("").reverse().join("");
            }
        }
    });
    

    两者之间的区别:
    methods:每次dom重新渲染。
    computed:dom渲染时有缓存。依据是实例内部的变量等,发生变化时,才会重新渲染。

    var app = new Vue({
        el: "#root",
        template: `<div>
            <input v-model="firstName">
            <input v-model="firstName">
            <div>{{fullName}}</div>
        </div>`,
        data: {
            firstName: "",
            lastName: ""
        },
        computed: {
            lastName: function() {//挡firstName,lastName这两个内部依赖变化时,就开始重新计算,依赖不变,使用缓存。
                return this.firstName + " " +this.lastName;
            }
        }
    });
    

    watch侦听属性

    var app = new Vue({
        el: "#root",
        template: `<div>
            <input v-model="firstName">
            <input v-model="firstName">
            <div>{{fullName}}</div>
        </div>`,
        data: {
            firstName: "",
            lastName: "",
            fullName: ""
        },
        watch: {
            firstName: function() {
                return this.fullName = this.firstName + " " +this.lastName;
            },
            lastName: function() {
                return this.fullName = this.first
            }
        }
    });
    

    相比较computed,computed的比较简洁。

    computed的set属性和get属性

    var app = new Vue({
        el: "#root",
        template: `<div>
            <input v-model="firstName">
            <input v-model="firstName">
            <div>{{fullName}}</div>
        </div>`,
        data: {
            firstName: "",
            lastName: ""
        },
        computed: {
            fullName: {
                get: function() {
                    return this.firstName+" "+this.lastName;
                },
                set: function(value) {
                    var arr = value.split("");
                    this.firstName = arr[0];
                    this.lastName = arr[1];
                }
            }
        }
    });
    

    demo:

    var app = new vue({
        el: "#root",
        templete: `
        <div id="watch-example">
            <p>
                Ask a yes/no question:
                <input v-model="question">
            </p>
            <p>{{answer}}</p>
        </div>
        `,
        data: {
            question: " ",
            answer: "I cannot give you an answer uniter you ask a question!"
        },
        watch: {
            question: function() {
                this.answer = "Wating for you to stop typing...";
                this.getAnster();
            }
        },
        methods: {
            getAnster: function() {
                if(this.question.indexOf("?") === -1) {
                    this.answer = "Questions usually contain a question mark.";
                    return ;
                }
                this.answer = "Thinking...";
                var _this = this;
    /*
                axios.get("https://yesno.wtf/api").then(function(response) {
                    _this.answer = response.data.answer;
                }).catch(function(error) {
                    _this.answer = "Error! Could not reach the API."+error;
                });
    */
                if(app.timer) {
                    clearTimer(app.timer);
                }
                app.timer = setTimeout(function() {
                    axios.get("https://yesno.wtf/api").then(function(response) {
                        _this.answer = response.data.answer;
                    }).catch(function(error) {
                        _this.answer = "Error! Could not reach the API."+error;
                    });
                },200);//利用定时器进行优化
            }
        }
    })
    
    

    class和style

    <div v-bind:class="{active: isActive}"></div>
    //active 类名, isActive: 布尔值
    <div v-bind:class="{active: isActive,'text-danager': hasError}"></div>
    //text-danager,中间有线,所以要加单引号。
    ...
    data: {
        isActive: true
    }
    computed: {
        hasError: function() {
            return false;
        }
    }
    //同样可以写在methods中实现,但不能重复实现过程。
    

    上面可等价:类的对象形式

    var app = new Vue({
        el: "#root",
        template: `<div v-bind:class="classObj">{{message}}</div>`,
        data: {
            message: "heelo world",
            isActive: true,
            hasError: false,
            classObj: {
                active: true,
                'text-danager': false
            }
        },
        computed: {//classObj也可以在computed中实现
            classObj: function() {
                return {
                    active: this.isActive,
                    'text-danger': this.hasError
                }
            }
        }
    });//case:tab
    

    类的数组形式

    var app = new Vue({
        el: "#root",
        template: `<div v-bind:class="[a,b]">{{message}}</div>`,
        data: {
            a: "active",
            b: "text-danger"
        },
        computed: {//classObj也可以在computed中实现
            classObj: function() {
                return {
                    active: this.isActive,
                    'text-danger': this.hasError
                }
            }
        }
    });
    

    内联样式:

    var app = new Vue({
        el: "#root",
        template: `<div v-bind:style="{fontSize: fontSize + 'px'}">{{message}}</div>`,
        data: {
            fontSize: 30
        }
    });
    

    内联样式的对象形式:

    var app = new Vue({
        el: "#root",
        template: `<div v-bind:style="styleObj">{{message}}</div>`,
        data: {
            styleObj: {
                color: "red",
                fonSize: "30px",
                display: ['-webkit-box', '-ms-flexbox', 'flex']//经过js处理在浏览器端会出现相应的属性
            }
        }
    });
    

    条件渲染

    多条件组选择:

    <template v-if="isTrue">
        <div>1</div>
        <div>2</div>
        <div>3</div>
    </template>
    <template v-else="isFalse">
        <div>1</div>
        <div>2</div>
        <div>3</div>
    </template>
    //在浏览器DOM中是不渲染的。
    v-if="条件表达式"
    
    <template v-if="number == 1">
        <div>1</div>
        <div>2</div>
        <div>3</div>
    </template>
    <template v-else-if="number == 2">
        <div>1</div>
        <div>2</div>
        <div>3</div>
    </template>
    <template v-else>
        <div>1</div>
        <div>2</div>
        <div>3</div>
    </template>
    var app = new Vue({
        el: "#root",
        data: {
            number: 1
        }
    })
    

    key值管理服用的元素

    <div id="root">
    <template v-if="loginType === 'username'">
        <label>UserName<label>
        <input placeholder="Enter your name" v-model="usename">
    </template>
    <template v-else>
        <label>Email<label>
        <input placeholder="Enter your email" v-model="email">
    </template>
    <button v-on:click="handleClick">toggle login style</button>
    </div>
    var app = new Vue({
        el: "#root",
        data: {
            loginType: "usename",
            username: "",//防止输入框中的数据清除
            email: ""
        },
        methods: {
            handleClick: function() {
                if(this.loginType === "username") {
                    this.loginType = "email";
                }else{
                    this.loginType = "username";    
                }
            }
        }
    });
    //这样使得切换的input输入的值不会发生变化,vue.js中处于对渲染的优化,解决办法在不同的input中添加key值,即可区分开来。这样有个小问题,切换之后输入框中的值不存在,分别绑定model值,即可解决。
    

    列表的渲染

    v-for="(item,key) in items"
    v-for="(item,key) of items"
    两者用法完全相同,
    
    <div v-for="(item, key, index) in object" v-bind:key="item.id">
    {{index}}{{key}}{{value}}
    </div>
    

    在遍历对象时,是按 Object.keys() 的结果遍历,但是不能保证它的结果在不同的 JavaScript 引擎下是一致的。
    这几种循环要谨慎使用,键值因不同的浏览器恶如输出不同的结果。循环的时候一般都要绑定key

    数组的方法:

    vue不会像新增内容上增加getter,setter,也就是双向绑定失效。所以对数组的操作要有新的语法。
    变异方法:也就是对原有数组的方法进行了改变。

    push();
    pop();
    shift();
    unshift();
    splice();
    sort();
    reverse();
    

    不能直接修改等,this.items[indexOfItem] = newValue。如下:

    this.items.push({ message: 'Baz' });
    

    事件

    <div id="root">
           <div id="counter-event-example">
            <p>{{total}}</p>
            <button-counter v-on:increment="incrementTotal"></button-counter>
            <button-counter v-on:increment="incrementTotal"></button-counter>
           </div>
       </div> 
    
       <script>
    //定义局部子组件
        var button = {
            template: `<button v-on:click="increment">{{counter}}</button>`,
            data: function() {
                return {
                    counter: 0
                }
            },
            methods: {
                increment: function() {
                    this.counter += 1;
                    this.$emit("increment");//自己点击时触发increment事件,父组件v-on:监听并执行此事件,incrementTotal事件
                }
            }
        };
    
       var App = new Vue({
           el: "#root",
           data: {
               total: 0
           },
           components: {//定义的子组件赋予新模板标记
               "button-counter": button
           },
           methods: {
               incrementTotal: function() {
                   this.total += 1;
               }
           }
       });
       </script>
    

    自定义一个简单的双向绑定

       <div id="root">
           <input v-bind:value="something" v-on:input="something = $event.target.value">
           <div>{{something}}</div>
       </div> 
    //v-bind 绑定一个值,v-on检测触发值的变化
       <script>
    //定义局部子组件
    
       var App = new Vue({
           el: "#root",
           data: {
               something: "" 
           },
       });
       </script>
    
    

    子组件与父组件的数据双向绑定

       <div id="root">
        <custom-input v-model="something"></custom-input>
        {{something}}
       </div> 
    //v-bind 绑定一个值,v-on检测触发值的变化
       <script>
    //定义局部子组件
        var custom = {
        template: `<input type="text" v-bind:value="value" v-on:input="handleInput">`,
            props: ["value"],//1.子组件接受一个value值就等于v-model绑定的值
            methods: {
                handleInput: function(e) {
                    this.$emit("input",e.target.value);
                }
            }
        }
    
       var App = new Vue({
           el: "#root",
           data: {
               something: "1212" 
           },
           components: {
                "custom-input": custom
           }
       });
       </script>
    
       <div id="root">
        <custom-input v-model="something"></custom-input>
        {{something}}
       </div> 
    //v-bind 绑定一个值,v-on检测触发值的变化
       <script>
    //定义局部子组件
        var custon = {
        template: `<input type="text" v-bind:check="value" v-on:input="handleInput"`>,
            props: ["value"],//1.子组件接受一个value值就等于v-model绑定的值
            methods: {
                handleInput: function(e) {
                    this.$emit("input",e.target.value);
                }
            }
        }
    
       var App = new Vue({
           el: "#root",
           data: {
               something: ture 
           },
           components: {
                "custom-input": custom
           }
       });
       </script>
    
  • 相关阅读:
    Codeforces Round #433 (Div. 1, based on Olympiad of Metropolises) B. Jury Meeting 贪心
    Codeforces Round #433 (Div. 1, based on Olympiad of Metropolises) A. Planning 优先队列
    forms组件的渲染错误信息,全局和局部钩子函数,cookie,session
    ajax处理urlencoded的装饰器,ajax上传文件,分页器组件,forms组件
    初识ajax
    django之手动创建第三张表 常用字段
    django之分组,聚合,F.Q.查询
    django的多表操作
    模板的导入和继承 单标操作
    day80 django模版学习
  • 原文地址:https://www.cnblogs.com/intelwisd/p/8647932.html
Copyright © 2011-2022 走看看