VUE入門筆記,第二節

VUE入門筆記,第二節

一、總結以上:實例-表格列表

【目標:實現表格數據的添加、刪除和過濾篩選】

【解決方案】

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>表格列表</title>
    <script src="./lib/vue-2.4.0.js"></script>
    <style>
        .tableStyle {
            margin: 20px auto;
            width: 500px;
            border-collapse: collapse;
        }
        .tableStyle tr>th,td{
            width: 60px;
            height:50px;
            text-align: center;
        }
        .search {
            margin: 50px auto;
            width:730px;
        }
    </style>
</head>
<body>
    
    <div id="app" >

        <div class="search">
            id: <input type="text" name="id" v-model="id">
            name: <input type="text" name="name" v-model="name">
            <input type="button" value="添加" @click="add(id,name)">
            search: <input type="text" name="search" v-model="keywords">
        </div>

        <table class="tableStyle" border="1">
            <tr>
                <th>id</th>
                <th>name</th>
                <th>cTime</th>
                <th>操作</th>
            </tr>
            <!-- <tr v-for="item in list" v-bind:key="item.id"> -->
            <tr v-for="item in search(keywords)" v-bind:key="item.id">
                <td>{{item.id}}</td>
                <td>{{item.name}}</td>
                <td>{{item.ctime}}</td>
                <td><a href="http://www.baidu.com" @click.prevent="remove(item.id)">刪除</a></td>
            </tr>
        </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:function(id,name){
                    let newArray = {id:id,name:name,ctime:new Date()};
                    this.list.push(newArray);
                },
                remove:function(id){
                    let newList = new Array();
                    this.list.forEach((item,index)=>{
                        if(item.id!=id){
                            newList.push(item);
                        }
                    });
                    this.list = newList;
                },
                search(keywords){
                    let newList = new Array();
                    this.list.forEach((item,index)=>{
                        if(item.name.indexOf(keywords)!=-1){
                            newList.push(item);
                        }
                    });
                    return newList;
                }
            }
        });

    </script>

</body>
</html>

結果:

在這裏插入圖片描述

二、過濾器

1、全局過濾器

【目標:將河北替換成邯鄲】

【解決方案】

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>過濾器vm.filter</title>
    <script src="./lib/vue-2.4.0.js"></script>
</head>
<body>

    <div id="app">
        <p>{{ msg | msgFormat }}</p>
    </div>
    
    <script>

        //定義一個vue全局過濾器,過濾器名稱叫做msgFormat
        //function第一個參數已經被定義死了,必須是過濾器管道符前面 傳遞過來的數據
        Vue.filter('msgFormat',function(msg){
            return msg.replace("河北","邯鄲");
        });

        var vm = new Vue({
            el: '#app',
            data:{
                msg: "我是河北人,我現在在北京"
            }
        });
    </script>

</body>
</html>

2、私有過濾器

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>過濾器vm.filter</title>
    <script src="./lib/vue-2.4.0.js"></script>
</head>
<body>

    <div id="app">
        <p>{{ msg | msgFormat("全局") }}</p>
    </div>

    <hr>

    <div id="app2">
        <p>{{ msg | msgFormat("私有") }}</p>
    </div>
    
    <script>

        //定義一個vue全局過濾器,過濾器名稱叫做msgFormat
        //function第一個參數已經被定義死了,必須是過濾器管道符前面 傳遞過來的數據
        Vue.filter('msgFormat',function(msg,flag){
            console.log(flag);
            return msg.replace("河北","邯鄲");
        });

        var vm = new Vue({
            el: '#app',
            data:{
                msg: "我是河北人,我現在在北京"
            }
        });


        var vm2 = new Vue({
            el: '#app2',
            data:{
                msg: "我是河北人,我現在在北京"
            },
            methods:{

            },
            filters:{   //定義私有過濾器,兩個條件: 過濾器名稱、處理函數

                //過濾器調用的時候,採用就近原則。如果私有過濾器和全局過濾器名稱一致,
                //這時候優先調用私有過濾器
                msgFormat:function(msg,flag){
                    console.log(flag);
                    return msg.replace("北京","石家莊");
                }
            }
        });

    </script>

</body>
</html>

三、按鍵修飾符

【目標:將案例-表格列表中 的添加按鈕,改成name按回車鍵直接添加】

【知識點:】

常用的按鍵修飾符:
.enter   #按回車鍵
.tab	 #按tab鍵
.delete	 #按delete鍵
.esc	 #按esc鍵
.space	 #按回車鍵
.up		 #按↑鍵
.down	 #按↓鍵
.left	 #按←鍵
.right	 #按→鍵

其他按鍵需要自定義,或者直接用鍵盤對應的按鍵編碼使用
	如:Vue.config.keyCodes.f2= 113;   將按鍵編碼爲113的f2鍵 自定義爲f2

【解決方案】

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>按鍵修飾符以及自定義</title>
    <script src="./lib/vue-2.4.0.js"></script>
    <style>
        .tableStyle {
            margin: 20px auto;
            width: 500px;
            border-collapse: collapse;
        }
        .tableStyle tr>th,td{
            width: 60px;
            height:50px;
            text-align: center;
        }
        .search {
            margin: 50px auto;
            width:730px;
        }
    </style>
</head>
<body>
    
    <div id="app" >

        <div class="search">
            id: <input type="text" name="id" v-model="id">
            <!--添加按鍵修飾符enter-->
            name-按鍵修飾符: <input type="text" name="name" v-model="name" @keyup.enter="add(id,name)">
            name-自定義按鍵修飾符: <input type="text" name="name" v-model="name" @keyup.f2="add(id,name)">
            <input type="button" value="添加" @click="add(id,name)">
            search: <input type="text" name="search" v-model="keywords">
        </div>

        <table class="tableStyle" border="1">
            <tr>
                <th>id</th>
                <th>name</th>
                <th>cTime</th>
                <th>操作</th>
            </tr>
            <!-- <tr v-for="item in list" v-bind:key="item.id"> -->
            <tr v-for="item in search(keywords)" v-bind:key="item.id">
                <td>{{item.id}}</td>
                <td>{{item.name}}</td>
                <td>{{item.ctime}}</td>
                <td><a href="http://www.baidu.com" @click.prevent="remove(item.id)">刪除</a></td>
            </tr>
        </table>
    </div>

    <script>

        Vue.config.keyCodes.f2= 113;

        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:function(id,name){
                    let newArray = {id:id,name:name,ctime:new Date()};
                    this.list.push(newArray);
                },
                remove:function(id){
                    let newList = new Array();
                    this.list.forEach((item,index)=>{
                        if(item.id!=id){
                            newList.push(item);
                        }
                    });
                    this.list = newList;
                },
                search(keywords){
                    let newList = new Array();
                    this.list.forEach((item,index)=>{
                        if(item.name.indexOf(keywords)!=-1){
                            newList.push(item);
                        }
                    });
                    return newList;
                }
            }
        });

    </script>

</body>
</html>

四、自定義指令

1、自定義全局指令

【目標:自定義指令,讓input框自動獲取焦點】

【知識點:】

//focus是指令名稱,但用的時候要用 <input v-focus>

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

【鉤子】
##bind:只調用一次,指令第一次綁定到元素時調用【只調用1次】---一般是樣式,如css樣式 color font-size等
##inserted:表示元素插入到DOM中的時候,就會執行【只調用1次】--一般是行爲,如js click keyup等
##updated:當window更新的時候,就會執行【制定多次】
    
如果鉤子是bind或update可以簡寫
Vue.directive('color-swatch', function (el, binding) {
  el.style.backgroundColor = binding.value
})
    
【參數】
//el是指令綁定的元素,可以用來直接操作原生DOM。默認第一個參數
//binding:
//    name: 指令名稱  如focus
//    value: 指令綁定的值  如blue 2
//    expression:指令綁定的表達式 如'blue' ‘1+1’
   	...

【測試】

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>自定義全局指令</title>
    <script src="./lib/vue-2.4.0.js"></script>
</head>
<body>
    
    <div id="app" >

        id:<input type="text" v-color="'red'" >
        name:<input type="text" v-focus>
    </div>

    <script>

        //inserted一般綁定js行爲
        Vue.directive('focus',{
            inserted:function(el){
                el.focus();
            }
        });

        //bind一般綁定css樣式
        Vue.directive('color',{
            bind:function(el,binding){
                console.log(el);
                console.log("name:"+binding.name+"  value:"+binding.value+"   expression:"+binding.expression);
                el.style.color=binding.value;
            }
        });

        var vm = new Vue({
            el: "#app",
            data:{
                
            },
            methods:{
                
            }
        });

    </script>

</body>
</html>

2、自定義私有指令

【知識點】

指令:
directives:{ //私有指令   指令名   處理函數
    'fontcolor': {
        bind: function (el,binding){
            console.log(binding.value);
            el.style.color='red';
        }
    }	
}

如果鉤子是bind和update可以簡寫如下:
directives:{ //私有指令   指令名   處理函數
	'fontsize':function(el,binding){
		el.style.fontSize=parseInt(binding.value)+"px";
	}
}

【方案:】

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>自定義私有指令</title>
    <script src="./lib/vue-2.4.0.js"></script>
</head>
<body>
    
    <div id="app" >

        id:<input type="text" v-color="'red'" >
        name:<input type="text" v-focus>

        <a v-fontcolor="'red'" v-fontsize="30">{{ msg }}</a>
    </div>

    <script>

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

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

        var vm = new Vue({
            el: "#app",
            data:{
                msg:'你好,我是私有指令'
            },
            methods:{
                
            },
            directives:{ //私有指令   指令名   處理函數
                'fontcolor': {
                    bind: function (el,binding){
                        console.log(binding.value);
                        el.style.color='red';
                    }
                },
                'fontsize':function(el,binding){ //如果鉤子是bind和update可以簡寫如下
                    el.style.fontSize=parseInt(binding.value)+"px";
                }
            }
        });

    </script>

</body>
</html>

五、VUE的生命週期

【知識點:】

VUE生命週期分類:
1、創建期間的生命週期函數
	beforeCreate:實例剛在內存中被創建出來,此時還沒有初始化好data和methods屬性
	created:實例已經在內存中創建OK,此時data和methods已經創建OK,此時還沒有開始編譯模板
	beforeMount:此時已經完成了模板的便已,但是還沒有掛載到頁面中
	mounted:此時,已經將便已好的模板,掛載到了頁面制定的容器中顯示
2、運行期間的生命週期函數
	beforeUpdate:狀態更新之前執行此函數,此時data中的狀態值是最新的,但是界面上顯示的數據
		還是舊的,應爲此時還沒有開始重新渲染DOM節點
	updated:實例更新完畢之後調用此函數,此時data中的狀態值 和 潔面上顯示的數據都已經完成了
		更新,潔面已經被重新渲染好了
3、銷燬期間的生命週期函數:
	beforeDestory:實例銷燬之前調用。在這一步,實例仍然完全可用
	destroyed:vue實例銷燬後調用。調用會後,vue實例指示的所有東西都會解綁,所有的時間監聽器
		會被移除,所有的子實例也會被銷燬

在這裏插入圖片描述

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>vue的生命週期</title>
    <script src="./lib/vue-2.4.0.js"></script>
</head>
<body>

    <div id="app">

        <input type="button" value="修改MSG" @click="msg='No'">

        <p id="h3">{{  msg }}</p>

    </div>

    <script>
        
        var vm = new Vue({
            el: '#app',
            data:{
                msg: 'ok'
            },
            methods:{
                show: function(){
                    console.log('執行了show方法');
                }
            },

            //1、創建期間的生命週期函數

            beforeCreate() {//這是我們遇到的第一個生命週期函數,表示實例完全被創建出來之前,會執行它
                // console.log(this.msg);
                // this.show();
                //注意:在beforeCreate生命週期函數執行的時候,data和methods中的數據都還沒有被初始化,所以都不能夠被調用
            },
            created() {//這是遇到的第二個生命週期函數
                // console.log(this.msg);
                // this.show();
                
                //注意:在created中data和methods都已經被初始化好了
                //如果要調用methods中的方法,或操作data中的數據,最早,只能在created中操作。
            },

            beforeMount() {//這是遇到的第三個生命週期函數,表示 模板已經在內存中編輯完成了,但是尚未把模板渲染到頁面中

                //console.log(document.getElementById("h3").innerText); //結果是 : {{ msg }}
                //注意:在beforeMount被執行的時候,頁面中的元素,還沒有被真正替換過來,只是之前寫的一些模板字符串
            },
            mounted() {//這是遇到的第四個生命週期函數,表示,內存中的模板,已經真實的掛載到了頁面中,用戶已經可以看到渲染好的頁面了
                
                //console.log(document.getElementById("h3").innerText); //結果是 : ok
                //注意: mounted是實例創建期間的最後一個生命週期函數,當執行完mounted就表示,實例
                //已經被完全創建好了,此時,如果沒有其他操作的話,這個實例就靜靜的躺在我們的內存中

            },


            //2、運行期間的生命週期函數(點擊更新MSG按鈕)
            beforeUpdate() {//這個時候表示我們的界面還沒有被更新,但是數據已經在內存中被更新了
                
                //console.log('界面上的內從:'+document.getElementById("h3").innerText);
                //console.log('data中的msg數據:'+this.msg);

                //結論:當執行beforeUpdate的時候,界面中的顯示數據還是 舊的OK,此時data數據是最新的No
                //頁面尚未和最新的數據保持同步
            },
            updated() {
                //console.log('界面上的內從:'+document.getElementById("h3").innerText);
                //console.log('data中的msg數據:'+this.msg);

                //updated事件執行的時候,頁面和data數據已經保持同步了
            },

            //3、銷燬期間的生命週期函數:
            beforeDestroy() {
                //當執行beforeDestroy 生命週期函數的時候,vue實例已經從運行階段,進入到了銷燬階段。
                //當執行beforeDestroy的時候,實例上所有的data和methods,以及過濾器,指令...仍處於可用狀態,
                //此時還沒有真正執行銷燬的過程
            },
            destroyed() {
                //當執行到destroyed函數的時候,組件已經被完全銷燬了,此時組件中所有的 數據 方法 指令 過濾器...
                //都已經不可用了
            },
        });

    </script>
    
</body>
</html>

六、vue-resource

vue-resource是一個第三方包,也可以使用axios等實現數據的請求【官網地址

【目標:vue-resource實現get、post、jsonp請求】

【常用方法:】

get(url, [config])
head(url, [config])
delete(url, [config])
jsonp(url, [config])
post(url, [body], [config])
put(url, [body], [config])
patch(url, [body], [config])

【案例:】

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>vue-resource第三方組件</title>
    <script src="./lib/vue-2.4.0.js"></script>
    <script src="./lib/vue-resource.js"></script>
</head>

<body>

    <div id="app">

        <input type="button" value="get按鈕" @click="dataGet">
        <input type="button" value="postget按鈕" @click="dataPost">
        <input type="button" value="jsonp按鈕" @click="dataJsonP">

        <p id="h3">{{  msg }}</p>

    </div>

    <script>

        var vm = new Vue({
            el: '#app',
            data: {
                msg: 'ok',
                addr1: 'xxxxxxxxxxxxxxxx',
                addr2: 'xxxxxxxxxxxxxxxx',
                addr3: 'xxxxxxxxxxxxxxxx'
            },
            methods: {
                dataGet() {
                    console.info('get')
                    this.$http.get(this.addr1, {
                        params: {
                            name: '1'
                        },
                        headers: {
                            token: 'a'
                        }
                    }).then(res => {
                        console.info(res.data)//返回成功函數
                    }, error => {
                        console.info(error)//返回失敗函數
                    })
                },
                dataPost() {
                    console.info('post')
                    this.$http.post(this.addr2, {
                        name: '1'
                    }, {
                        headers: {
                            token: 'a'
                        }
                    }).then(res => {
                        console.info(res.data)//返回成功函數
                    }, error => {
                        console.info(error)//返回失敗函數
                    })
                },
                dataJsonP() {
                    console.info('jsonp')
                    this.$http.jsonp(this.addr3, {
                        params: {
                            name: '1'
                        }
                    }).then(res => {
                        console.info(res.data)//返回成功函數
                    }, error => {
                        console.info(error)//返回失敗函數
                    })
                }

            });

    </script>

</body>

</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章