vue2練習五個小例子筆記_byKL

線上猛如虎發表於2017-02-22

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過濾器

相關文章