2

vue2练习五个小例子笔记

多练习,多撸代码,多进步.

1.双向数据绑定

<!--vue实例上绑定click事件hideTooltip-->
<div id="main" @click="hideTooltip">
<!--v-if判断show_tooltip,为true则显示,并且绑定了一个阻止单击事件冒泡-->
  <div class="tooltip" v-if="show_tooltip" @click.stop>
  <!--用v-modal绑定了text_content,能够双向更新数据-->
    <input type="text" v-model="text_content" />
  </div>
  <!--因为双向绑定的关系,所以这里可以一边输入,一边输出内容-->
  <p @click.stop="toggleTooltip">{{text_content}}</p>
</div>
  1. .stop这种用法是vue的一种语法糖,名叫事件修饰符,这里的是阻止单击事件冒泡

  2. @这种也是一种vue的语法糖,名叫缩写,绑定事件的缩写

var demo = new Vue({
  el: '#main',
  data: {
    show_tooltip: false, //给v-if判断使用的布尔值
    text_content: 'Edit me.'
  },
  methods: {
  //click绑定的事件
    hideTooltip: function() {
      this.show_tooltip = false; //this可以调用当前vue实例的内容,也就是说this指向当前vue实例的作用域
    },
    //true/false的切换,他们的切换会直接硬性v-if的判断,从而实现隐藏和出现的效果
    toggleTooltip: function() {
      this.show_tooltip = !this.show_tooltip;
    }
  }
});

demo

2.导航切换

<div id="main">
    <nav @click.prevent>
    <!--v-for遍历输出内容,并且绑定了class-->
<!--        <a v-for="item in items" :class="{'show': item.active}" @click="makeActive(item, $index)">{{item.name}}</a>-->
<!--之前写法有问题,没检查好,css无法切换-->
      <a v-for="(item,index) in items" :class="{'show': item.active}" @click="makeActive(item,index)">
            {{item.name}}
        </a>
    </nav>
    <p>You chose <b>{{active}}</b></p>
</div>
  1. .prevent阻止默认事件,这里主要是为了阻止a标签的点击自动跳转或者刷新页面的默认事件

  2. :是vue的缩写,v-bind的缩写

  3. show 的更新将取决于数据属性 item.active 是否为真值,参考绑定class

  4. makeActive(item, index)这个是最主要的,控制item的active属性

    • v-for是通过一个对象的属性来迭代的,items的key就是0123,value就是item对象,所以转换一下方便看,将key和vaule转为item和idnex

    • 参考官网

var vm = new Vue({
    el:'#main',
    data:{
        active:'HTML', 
        items:[ //被遍历的数组
            {name:'HTML', active:true}, //通过控制active的值(布尔值)来做一些处理,例如为true的时候show,为false的hide
            {name:'CSS', active:false},
            {name:'JavaScript', active:false},
            {name:'Vue.js', active:false}
        ]
    },
    methods: {
        makeActive: function(item, index){ //使用传入的当前的v-for循环的遍历项和当前索引
            this.active = item.name; 
        for(var i=0; i<this.items.length;i++){//将所有item设置为false
            this.items[i].active = false;
        }
        this.items[index].active = true;//然后单独设置选中的item为true
        }
    }
});

参考demo

3.即时搜索

<div id="main">
    <div class="bar">
    <!--v-modal的双向绑定-->
        <input type="text" v-model="searchStr" placeholder="Enter your search terms"/>
    </div>
    <ul>
    <!--这里使用了articles1来做特别标志,证明这个计算属性不是在data里面的,而是通过计算出来的-->
    <!--通过遍历计算属性articles1来输出需要的信息-->
        <li v-for="a in articles1">
            <a :href="a.url"><img :src="a.image"/></a>
            <p>{{a.title}}</p>
        </li>
    </ul>
</div>
    new Vue({
        el: '#main',
        data: {
            searchStr: "", //双向绑定的属性
            articles: [
                {
                    "title": "What You Need To Know About CSS Variables",
                    "url": "http://tutorialzine.com/2016/03/what-you-need-to-know-about-css-variables/",
                    "image": "http://cdn.tutorialzine.com/wp-content/uploads/2016/03/css-variables-100x100.jpg"
                },
                {
                    "title": "Freebie: 4 Great Looking Pricing Tables",
                    "url": "http://tutorialzine.com/2016/02/freebie-4-great-looking-pricing-tables/",
                    "image": "http://cdn.tutorialzine.com/wp-content/uploads/2016/02/great-looking-pricing-tables-100x100.jpg"
                },
                {
                    "title": "20 Interesting JavaScript and CSS Libraries for February 2016",
                    "url": "http://tutorialzine.com/2016/02/20-interesting-javascript-and-css-libraries-for-february-2016/",
                    "image": "http://cdn.tutorialzine.com/wp-content/uploads/2016/02/interesting-resources-february-100x100.jpg"
                },
                {
                    "title": "Quick Tip: The Easiest Way To Make Responsive Headers",
                    "url": "http://tutorialzine.com/2016/02/quick-tip-easiest-way-to-make-responsive-headers/",
                    "image": "http://cdn.tutorialzine.com/wp-content/uploads/2016/02/quick-tip-responsive-headers-100x100.png"
                },
                {
                    "title": "Learn SQL In 20 Minutes",
                    "url": "http://tutorialzine.com/2016/01/learn-sql-in-20-minutes/",
                    "image": "http://cdn.tutorialzine.com/wp-content/uploads/2016/01/learn-sql-20-minutes-100x100.png"
                },
                {
                    "title": "Creating Your First Desktop App With HTML, JS and Electron",
                    "url": "http://tutorialzine.com/2015/12/creating-your-first-desktop-app-with-html-js-and-electron/",
                    "image": "http://cdn.tutorialzine.com/wp-content/uploads/2015/12/creating-your-first-desktop-app-with-electron-100x100.png"
                }
            ]
        },
        computed: { //使用计算属性
            articles1: function () { //这个articles1就是计算属性
                if(!this.searchStr){ //没有输入搜索项就不处理
                    return false;
                }
                var s = this.searchStr.trim().toLowerCase();
                //使用js的filter遍历循环,通过在这里处理循环之后然后返回处理好的数组给v-for进行处理
                var result = this.articles.filter(function (item) {
                    if (item.title.toLowerCase().indexOf(s) !== -1) {
                        return item;
                    }
                });
                return result;
            }
        }
    });

demo例子使用vue1,然后jsfiddle已经升级了vue2了,vue2抛弃了大部分过滤器,所以无法运行(vue2的过滤器升级),在这里我稍微修改了一下,使用vue2写法来实现

4.布局切换

<div id="main">
    <div class="bar">
        <!--v-bind绑定class的用法,并且通过click改变layout属性-->
        <a class="grid-icon" v-bind:class="{ 'active': layout == 'grid'}" v-on:click="layout = 'grid'"></a>
        <a class="list-icon" v-bind:class="{ 'active': layout == 'list'}" v-on:click="layout = 'list'"></a>
    </div>
    <!--v-if判断layout属性的变化来切换显示-->
    <ul v-if="layout == 'grid'" class="grid">
        <li v-for="a in articles">
            <a v-bind:href="a.url" target="_blank"><img v-bind:src="a.image.large" /></a>
        </li>
    </ul>
    <ul v-if="layout == 'list'" class="list">
        <li v-for="a in articles">
            <a v-bind:href="a.url" target="_blank"><img v-bind:src="a.image.small" /></a>
            <p>{{a.title}}</p>
        </li>
    </ul>
</div>
    /*bar的icon用了base64的图*/
    .bar a.list-icon{
        background-image:url(data:image/png;base64,iVBORw0KGgXXXXXX);
    }

    .bar a.grid-icon{
        background-image:url(data:image/png;base64,iVBORw0XXXXXXX);
    }
    /*grid和list两种布局的css都写好了,只要相对切换.gird或者.list就可以实现变化*/
    ul.grid{
        width: 570px;
        margin: 0 auto;
        text-align: left;
    }
    ul.grid li{
        padding: 2px;
        float:left;
    }
    ul.grid li img{
        width:280px;
        height:280px;
        object-fit: cover;
        display:block;
        border:none;
    }
    ul.list{
        width: 500px;
        margin: 0 auto;
        text-align: left;
    }

    ul.list li{
        border-bottom: 1px solid #ddd;
        padding: 10px;
        overflow: hidden;
    }

    ul.list li img{
        width:120px;
        height:120px;
        float:left;
        border:none;
    }

    ul.list li p{
        margin-left: 135px;
        font-weight: bold;
        color:#6e7a7f;
    }
   var demo = new Vue({
        el: '#main',
        data: {
            layout: 'grid',
            articles: [{
                "title": "What You Need To Know About CSS Variables",
                "url": "http://tutorialzine.com/2016/03/what-you-need-to-know-about-css-variables/",
                "image": {
                    "large": "http://cdn.tutorialzine.com/wp-content/uploads/2016/03/css-variables.jpg",
                    "small": "http://cdn.tutorialzine.com/wp-content/uploads/2016/03/css-variables-150x150.jpg"
                }
            },
                {
                    "title": "Freebie: 4 Great Looking Pricing Tables",
                    "url": "http://tutorialzine.com/2016/02/freebie-4-great-looking-pricing-tables/",
                    "image": {
                        "large": "http://cdn.tutorialzine.com/wp-content/uploads/2016/02/great-looking-pricing-tables.jpg",
                        "small": "http://cdn.tutorialzine.com/wp-content/uploads/2016/02/great-looking-pricing-tables-150x150.jpg"
                    }
                },
                {
                    "title": "20 Interesting JavaScript and CSS Libraries for February 2016",
                    "url": "http://tutorialzine.com/2016/02/20-interesting-javascript-and-css-libraries-for-february-2016/",
                    "image": {
                        "large": "http://cdn.tutorialzine.com/wp-content/uploads/2016/02/interesting-resources-february.jpg",
                        "small": "http://cdn.tutorialzine.com/wp-content/uploads/2016/02/interesting-resources-february-150x150.jpg"
                    }
                },
                {
                    "title": "Quick Tip: The Easiest Way To Make Responsive Headers",
                    "url": "http://tutorialzine.com/2016/02/quick-tip-easiest-way-to-make-responsive-headers/",
                    "image": {
                        "large": "http://cdn.tutorialzine.com/wp-content/uploads/2016/02/quick-tip-responsive-headers.png",
                        "small": "http://cdn.tutorialzine.com/wp-content/uploads/2016/02/quick-tip-responsive-headers-150x150.png"
                    }
                },
                {
                    "title": "Learn SQL In 20 Minutes",
                    "url": "http://tutorialzine.com/2016/01/learn-sql-in-20-minutes/",
                    "image": {
                        "large": "http://cdn.tutorialzine.com/wp-content/uploads/2016/01/learn-sql-20-minutes.png",
                        "small": "http://cdn.tutorialzine.com/wp-content/uploads/2016/01/learn-sql-20-minutes-150x150.png"
                    }
                },
                {
                    "title": "Creating Your First Desktop App With HTML, JS and Electron",
                    "url": "http://tutorialzine.com/2015/12/creating-your-first-desktop-app-with-html-js-and-electron/",
                    "image": {
                        "large": "http://cdn.tutorialzine.com/wp-content/uploads/2015/12/creating-your-first-desktop-app-with-electron.png",
                        "small": "http://cdn.tutorialzine.com/wp-content/uploads/2015/12/creating-your-first-desktop-app-with-electron-150x150.png"
                    }
                }]

        }
    });

demo

5.合计总价

<div id="main" v-cloak>
    <h1>Services</h1>
    <ul>
        <!--v-for遍历,绑定click监听,切换active-->
        <!--将currency filter的写法更换为toFixed-->
        <li v-for="item in items" @click="toggleActive(item)" :class="{'active':item.active}">{{item.name}}<span>{{item.price.toFixed(2)}}</span></li>
    </ul>
    <!--这里注意的是直接使用vue的方法的写法-->
    <p>Total: <span>{{total()}}</span></p>
</div>

依然修改了vue2的filter的使用

    var demo = new Vue({
        el: '#main',
        data: {
            items: [
                {
                    name: 'Web Development',
                    price: 300,
                    active:false
                },{
                    name: 'Design',
                    price: 400,
                    active:false
                },{
                    name: 'Integration',
                    price: 250,
                    active:false
                },{
                    name: 'Training',
                    price: 220,
                    active:false
                }
            ]
        },
        methods: {
            toggleActive: function(i){
                i.active = !i.active; //简单的写法切换true/false
            },
            total: function(){
                var total = 0;
                this.items.forEach(function(s){ //用js的forEach遍历数组
                    if (s.active){ //只要判断active才会处理计算
                        total+= s.price;
                    }
                });
                return total.toFixed(2);//将currency filter的写法更换
            }
        }
    });

demo

参考引用:

  1. 学习vue.js的五个小例子

  2. 纪念即将逝去的Vue过滤器


线上猛如虎
2.2k 声望178 粉丝

你们都有梦想的,是吧.怀抱着梦想并且正朝着梦想努力的人,寻找着梦想的人,我想为这些人加油呐喊!