Vue第二部分

品牌列表案例

運(yùn)用的知識:

v-model進(jìn)行雙向綁定

@click.prevent="del(id)" 函數(shù)傳參

v-for循環(huán)

String.prototype.includes('要包含的字符串')

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>cysky</title>
    <link rel="stylesheet" href="../lib/bootstrap-3.3.7.css">
    <script src="../lib/vue-2.4.0.js"></script>
</head>
<body>
<div id="app">
    <div class="panel panel-primary">
        <div class="panel-heading">
            <h3>添加品牌</h3>
        </div>
        <div class="panel-body form-inline">
            <label for="">
                ID:
                <input type="text" class="form-control" v-model="id">
            </label>
            <label for="">
                Name:
                <input type="text" class="form-control" v-model="name">
            </label>
            <label for="">
                <input type="button" value="添加" class="btn btn-primary" @click="add">
            </label>
            <label for="">
                搜索名稱關(guān)鍵字:
                <input type="text" class="form-control" v-model="keywords">
            </label>
        </div>
    </div>

    <table class="table table-bordered table-striped table-hover">
        <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Ctime</th>
            <th>Del</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="item in search(keywords)">
            <td>{{ item.id }}</td>
            <td>{{ item.name }}</td>
            <td>{{ item.ctime }}</td>
            <td><a href="" @click.prevent="del(id)">刪除</a></td>
        </tr>
        </tbody>
    </table>
</div>

<script>
    var vm = new Vue({
        el: '#app',
        data: {
            id: '',
            name: '',
            keywords: '',
            list: [
                {id: 1, name: '奔馳', ctime: new Date()},
                {id: 2, name: '寶馬', ctime: new Date()},
            ]

        },
        methods: {
            add() {
                var car = {id: this.id, name: this.name, ctime: new Date()};
                this.list.push(car);
                this.id = '';
                this.name = ''
            },
            del(id) {
                var index = this.list.indexOf(function (item) {
                    if (item.id === id) {
                        return true
                    }
                });
                this.list.splice(index, 1)
            },
            search(keywords) {
                return this.list.filter(function (item) {
                    if (item.name.includes(keywords)) {
                        return item
                    }
                })
            }
        }
    })
</script>
</body>
</html>

<tr v-for="item in search(keywords)">

之前,v-for 中的數(shù)據(jù),都是直接從 data 上的 list 中直接渲染過來的,現(xiàn)在,這里定義了一個 search 方法 在 search 方法內(nèi)部,通過執(zhí)行 for 循環(huán),把所有符合搜索的關(guān)鍵字的數(shù)據(jù),保存到一個新數(shù)組中返回。

全局過濾器

定義私有過濾器 過濾器有兩個 條件 【過濾器名稱 和 處理函數(shù)】

所謂的全局過濾器,就是所有的VM實(shí)例都共享的

Vue.filter('dataFormat',function(dataStr,pattern = ''){
        var dt = new Date(dataStr);
        var y = dt.getFullYear();
        var m = dt.getMonth()+1;
        var d = dt.getDate().toString().padStart(2,'0');
        var h = dt.getHours().toString().padStart(2,'0');
        var mm = dt.getMinutes().toString().padStart(2,'0');
        var s = dt.getSeconds().toString().padStart(2,'0');
        return `${y}-${m}-$u0z1t8os ${h}:${mm}:${s}`
    });

使用: <td>{{ item.ctime | dateFormat() }}</td>

私有過濾器

過濾器調(diào)用的時候,采用就近原則,如果私有過濾器和全局過濾器名稱一致,這時候優(yōu)先調(diào)用私有過濾器

filters:{
            timeFormat: function (dateStr, pattern='') {
                var dt = new Date(dateStr);
                var y = dt.getFullYear();
                var m = dt.getMonth() + 1;
                var d = dt.getDate();
                var h = dt.getHours().toString().padStart(2,'0');
                var mm = dt.getMinutes().toString().padStart(2,'0');
                var s = dt.getSeconds().toString().padStart(2,'0');
                return `${y}-${m}-$u0z1t8os ${h}:${mm}:${s}`
            }
        }

自定義全局按鍵修飾符

全部的按鍵別名:

  • .enter
  • .tab
  • .delete (捕獲“刪除”和“退格”鍵)
  • .esc
  • .space
  • .up
  • .down
  • .left
  • .right

以上可以直接使用:@click.enter = 'add'

Vue.config.keyCodes.f2 = 113

使用:@click.f2='add'

使用Vue.directive()定義全局的指令

 Vue.directive('focus',{
        inserted:function(el){
            el.focus()
        }
    });

使用:<input type="text" class="form-control" v-model="keywords" id="search" v-focus v-color="'green'">

inserted 表示元素 插入到DOM中的時候,會執(zhí)行 inserted 函數(shù)【觸發(fā)1次】

和樣式相關(guān)的操作,一般都可以在 bind 執(zhí)行

    Vue.directive('color',{
        bind:function(el,binding){
            el.style.color = 'red';
            console.log(binding.value)
        }
    });

使用:<input type="text" class="form-control" v-model="keywords" id="search" v-focus v-color="'green'">

每當(dāng)指令綁定到元素上的時候,會立即執(zhí)行這個 bind 函數(shù),只執(zhí)行一次

函數(shù)中的第一個參數(shù)永遠(yuǎn)是 el ,表示被綁定了指令的那個元素, 這個 el 參數(shù), 是一個原生的 JS 對象

和 JS 行為有關(guān)的操作,最好在 inserted 中去執(zhí)行

參數(shù)1:指令的名稱,注意,在定義的時候,指令名稱前不需要加 v- 前綴,但是,在調(diào)用的時候,必須在指令名稱前加上 v- 前綴來進(jìn)行調(diào)用

參數(shù)2:是一個對象,這個對象身上,有一些指令相關(guān)的函數(shù),這些函數(shù)可以在特定階段,執(zhí)行相關(guān)的操作

自定義私有指令

 directives: {
            'fontweight': {
                bind: function (el, binding) {
                    el.style.fontWeight = binding.value
                }
            },
            'fontsize': {
                bind: function (el, binding) {
                    el.style.fontSize = binding.value
                }
            }
        }

品牌列表完整案例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>cysky</title>
    <link rel="stylesheet" href="../lib/bootstrap-3.3.7.css">
    <script src="../lib/vue-2.4.0.js"></script>
</head>
<body>
<div id="app">
    <div class="panel panel-primary">
        <div class="panel-heading">
            <h3>添加品牌</h3>
        </div>
        <div class="panel-body form-inline">
            <label for="">
                ID:
                <input type="text" class="form-control" v-model="id">
            </label>
            <label for="">
                Name:
                <input type="text" class="form-control" v-model="name">
            </label>
            <label for="">
                <input type="button" value="添加" class="btn btn-primary" @click="add">
            </label>
            <label for="">
                搜索名稱關(guān)鍵字:
                <input type="text" class="form-control" v-model="keywords" v-focus>
            </label>
        </div>
    </div>

    <table class="table table-bordered table-striped table-hover">
        <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Ctime</th>
            <th>Del</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="item in search(keywords)">
            <td>{{ item.id }}</td>
            <td>{{ item.name }}</td>
            <td>{{ item.ctime | timeFormat() }}</td>
            <td><a href="" @click.prevent="del(id)">刪除</a></td>
        </tr>
        </tbody>
    </table>

    <p v-fontsize="50" v-color="'blue'">這是一個P標(biāo)簽,用于測試私有directives</p>
</div>

<script>
    var vm = new Vue({
        el: '#app',
        data: {
            id: '',
            name: '',
            keywords: '',
            list: [
                {id: 1, name: '奔馳', ctime: new Date()},
                {id: 2, name: '寶馬', ctime: new Date()},
            ]

        },
        methods: {
            add() {
                var car = {id: this.id, name: this.name, ctime: new Date()};
                this.list.push(car);
                this.id = '';
                this.name = ''
            },
            del(id) {
                var index = this.list.indexOf(function (item) {
                    if (item.id === id) {
                        return true
                    }
                });
                this.list.splice(index, 1)
            },
            search(keywords) {
                return this.list.filter(function (item) {
                    if (item.name.includes(keywords)) {
                        return item
                    }
                })
            }

        },
        filters: {//私有過濾器
            timeFormat: function (dateStr, pattern = '') {
                var dt = new Date(dateStr);
                var y = dt.getFullYear();
                var m = dt.getMonth() + 1;
                var d = dt.getDate();
                var h = dt.getHours().toString().padStart(2, '0');
                var mm = dt.getMinutes().toString().padStart(2, '0');
                var s = dt.getSeconds().toString().padStart(2, '0');
                return `${y}-${m}-$u0z1t8os ${h}:${mm}:${s}`
            }
        },
        directives: {//自定義私有指令
            'fontweight': {
                bind: function (el, binding) {
                    el.style.fontWeight = binding.value
                }
            },
            'fontsize': {
                bind: function (el, binding) {
                    el.style.fontSize = parseInt(binding.value) + 'px'
                }
            },
            'color': {
                bind: function (el, binding) {
                    el.style.color = binding.value
                }
            },
            'focus': {
                inserted: function (el) {
                    el.focus()
                }
            }
        }
    })
</script>
</body>
</html>

生命周期

lifecycle.png

beforeCreate(){}:這是我們遇到的第一個生命周期函數(shù),表示實(shí)例完全被創(chuàng)建出來之前,會執(zhí)行它

注意:beforeCreate(){} 執(zhí)行的時候,data 和 methods 中的數(shù)據(jù)都還沒有初始化

created(){} 這是遇到的第二個生命周期函數(shù),在 created 中,data 和 methods 都已經(jīng)被初始化好了

注意:如果要調(diào)用 methods 中的方法,或者操作 data 中的數(shù)據(jù),最早,只能在 created 中操作

beforeMount(){} 這是遇到的第三個生命周期函數(shù),表示模版已經(jīng)在內(nèi)存中編輯完成了,但是尚未把模版渲染到頁面中

注意:在 beforeMount 執(zhí)行的時候,頁面中的元素,還沒有被真正替換過來,只是之前寫的模版字符串

mounted(){} 這是遇到的第四個盛名周期函數(shù),表示,內(nèi)存中的模版,已經(jīng)真實(shí)的掛載到了頁面中,用戶已經(jīng)可以看到渲染好的頁面了

注意:mounted 是實(shí)例創(chuàng)建期間最后的一個生命周期函數(shù),當(dāng)執(zhí)行完 mounted 就表示,實(shí)例已經(jīng)被完全創(chuàng)建好了,此時,如果沒有其他操作,這個實(shí)例就在內(nèi)存中,等候

接下來的是運(yùn)行中的兩個事件

beforeUpdate() {} 這時候表示我們的界面還沒有被更新(數(shù)據(jù)已經(jīng)更新了)

結(jié)論: 當(dāng)執(zhí)行 beforeUpdate 的時候,頁面中的顯示的數(shù)據(jù),還是舊的,此時 data 數(shù)據(jù)是最新的,頁面尚未和 最新的數(shù)據(jù)保持同步

updated(){} 事件執(zhí)行的時候,頁面和 data 數(shù)據(jù)已經(jīng)保持同步了,都是最新的

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • vue概述 在官方文檔中,有一句話對Vue的定位說的很明確:Vue.js 的核心是一個允許采用簡潔的模板語法來聲明...
    li4065閱讀 7,624評論 0 25
  • ## 框架和庫的區(qū)別?> 框架(framework):一套完整的軟件設(shè)計(jì)架構(gòu)和**解決方案**。> > 庫(lib...
    Rui_bdad閱讀 3,155評論 1 4
  • 想起了《記承天寺夜游》,元豐六年十月十二日夜,解衣欲睡,月色入戶,欣然起行。念無與為樂者,遂至承天寺,尋張懷民,...
    逃離者閱讀 441評論 0 1
  • Peter同學(xué)乃濱海小外四年級小學(xué)生一枚,時有妙語引家人一樂,故記錄之。 論好食堂的重要性 四年級開學(xué)在即,當(dāng)老師...
    胡喜平閱讀 824評論 0 3
  • 人有三次成長,我經(jīng)歷了兩次,有些事情不是努力可以得到的…… 我今年18,摩羯座,馬上大二,在這個暑假,我第一次覺得...
    我就是很普通閱讀 520評論 0 1

友情鏈接更多精彩內(nèi)容