VUE初級入門實踐

VUE概述

生命周期

<script>
    new Vue({
        el:"#demo",
        data:{
            name:"Hello"
        },
        template:`
            <div>
                <p>{{name}}</p>
                <input v-model="name" />
            </div>
        `,
        beforeCreate:function(){
            console.log("創(chuàng)建之前")
            console.log(this.$el)//undefined
            console.log(this.$data)//undefined
        },
        // created 讀取數(shù)據(jù)
        created:function(){
            console.log("創(chuàng)建之后")
            console.log(this.$el)//undefined
            console.log(this.$data)//有
        },
        //beforeCompile  
        beforeMount:function(){
            console.log("掛載之前")
            console.log(this.$el)//有
            console.log(this.$data)//有
            console.log(document.querySelector("#demo"))//只有節(jié)點,無數(shù)據(jù)
        },
        //ready
        mounted:function(){
            console.log("掛載之后")
            console.log(this.$el)//有
            console.log(this.$data)//有
        },
        beforeUpdate:function(){
            console.log("更新之前")
            console.log(this.$el)//有
            console.log(this.$data)//有
            console.log(document.querySelector("body"))
        },
        updated:function(){
            console.log("更新之后")
            console.log(this.$el)//有
            console.log(this.$data)//有
            console.log(document.querySelector("body"))
        }
    })
</script>

指令

內(nèi)置指令

    <!--1.v-text/ng-bind  -->
    <p v-text="name"></p>

    <!-- 2.v-html/ng-bind-html -->
    <p v-html="html"></p>

    <!-- 3.v-if/ng-if -->
    <p v-if="bool">v-if 真</p>

    <!-- 4.v-else !bool / ng-hide -->
    <p v-else>v-else 假</p>

    <!-- 5.v-show/ng-show -->
    <p v-show="bool">v-show 真</p>

    <!-- 6.v-for/ng-repeat -->
    <ul>
        <li v-for="a in arr" track-by="$index" id="{{$index}}">{{a}}</li>
    </ul>

    <!-- 7.v-on:click/ng-click -->
    <button v-on:click="ok()">ok1</button>
    <button @click="ok()">ok2(簡寫)</button>

    <!-- 8.v-bind:class && v-bind:style /ng-class&&ng-style -->
    <p v-bind:class="{blue:bool}">class類名1</p>
    <p :class="{blue:bool}">class類名2(簡寫)</p>

    <!-- 9.v-model -->
    <input type="range" v-model="size" />
    <p v-bind:style="{fontSize:size + 'px'}">字體大小</p>
    <p :style="{fontSize:size + 'px'}">字體大小2(簡寫)</p>

    <!-- 10 給id起名字,注意:1)'name'是字符串,name是變量; 2): 冒號可以省略{{}}(表達式) -->
    <p :id="'name'+name" class="yellow">屬性值</p>

自定義指令

// 指令的簡單寫法 vue 2.0 // 這里將會被 `bind` 和 `update` 調(diào)用
Vue.directive('color', function(ele, attr) {
    //1.獲取指令中的屬性值;
    ele.style.color = attr.expression
    console.log(attr)

    //2.獲取非標準屬性的屬性值;
    var skill = ele.getAttribute("skill")
    console.log(skill);
});

過濾器

內(nèi)置過濾器

  • VUE1.0版本
<div id="demo">
        <p style="color: red;">1.currency</p>
        <p>{{num|currency "¥" 5}}</p>
        <p style="color: red;">2.lowercase</p>
        <p>{{name|lowercase}}</p>
        <p style="color: red;">3.uppercase</p>
        <p>{{name|uppercase}}</p>
        <p style="color: red;">4.pluralize(復數(shù)) 特有</p>
        <p>{{date}}{{date|pluralize 'st' 'nd' 'rd' 'th'}}</p>
        <p style="color: red;">5.json</p>
        <p>{{obj|json 10}}</p>
        <p style="color: red;">6.debounce(延遲器) 特有</p>
        <button @click="ok()|debounce 2000">ok</button>
        <p style="color: red;">7.capitalize(首字母大寫) 特有</p>
        <p>{{name|capitalize}}</p>
        <p style="color: red;">8.orderBy</p>
        <ul>
            <li v-for="arr in arrs|orderBy 'age' -1">{{arr.name}} {{arr.age}}</li>
        </ul>
        <p style="color: red;">9.filterBy</p>
        <input v-model="search" />
        <ul>
            <li v-for="arr in arrs|filterBy search in 'name'">{{arr.name}} {{arr.age}}</li>
        </ul>
        <p style="color: red;">9.limitBy</p>
        <input v-model="search" />
        <ul>
            <li v-for="arr in arrs|limitBy 2 1">{{arr.name}} {{arr.age}}</li>
        </ul>
        <p>{{name|limitBy 2 2}}</p>
    </div>
  • VUE2.0版本(無內(nèi)置過濾器)

自定義過濾器

<script>
        Vue.filter("ed",function(input){
            return input + "ed";
        });
        new Vue({
            el:"#demo",
            template:`
            <p>{{name|ed}}</p>
            `,
            data:{
                name:"heightzhang"
            }
        })
</script>

組件

DEMO 完整的組件模版(prop,filters,directives,components)

Vue.component('xheader', {
            props:["message"], //主組件向子組件傳遞數(shù)據(jù); 
            template: `
                <div style="border:1px solid green">
                    <p v-color="'red'">{{name|ed}}</p>
                    <button @click="ok()">ok</button>
                    <p v-if="message=='1'">1</p>
                </div>
            `,
            data: function() { 注意://組件中的data 必須是一個函數(shù);
                return {
                    name: "第一個組件"
                }
            },
            methods: {  //組件中的方法;
                ok: function() {
                    console.log("ok")
                }
            }, 
            filters: { //組件中的過濾器
                ed: function(input) {
                    return input + "ed";
                }
            },
            directives: { //組件中的的指令
                color: function(el, binding, vnode) {
                    console.log(el)
                    el.style.color = binding.value
                }
            },
            mounted:function(){ //組件中的JS邏輯
                console.log(this.message)  //橋梁props ,接收message;
            },
            components: { 組件中的嵌套;
                xcontentheader: {
                    props: ["imgUrl"],
                    template: `
                        <div class="weui-media-box__hd"  >
                             ![](imgUrl)
                         </div>
                     `,
                     methods:{
                         setImg(imgUrl){
                        this.$store.dispatch('setImg',[imgUrl,true])
                    }
                }
             }
        })

通信

父組件向子組件(props)

<script>
//----------子組件
        Vue.component('xheader', {
            props: ["message"], //接收父組件的非標準屬性
            template: `
                <div style="border:1px solid green">
                    <p>{{message}}</p>  //打印出來 =>變量name =>laoyao 
                </div>
            `,
            data: function() {
                return {
                    name: "第一個組件"
                }
            }
        })
//---------父組件-----------
        new Vue({
            el: "#demo",
            data: {
                name: "laoyao"
            },
            computed: {
                named: function() {
                    this.ok()
                    return this.name + "ed"
                }
            },
            template: `
                <div>
                    <input v-model="name" />
                    <xheader :message="name"></xheader> //父組件的非標準屬性(傳遞變量name)
                    <p>{{named}}</p>
                </div>
            `,
            methods: {
                ok: function() {
                    console.log("ok")
                }
            }
        })
    </script>

子組件向父組件 / 兄弟組件之間

VUEX

DEMO(子組件xlist向xgallery傳遞數(shù)據(jù))


index中心

<script>
// 新建一個狀態(tài)管理:
var store = new Vuex.Store({
    state:{  //全局數(shù)據(jù)的集中棧
        imgUrl:null,
        isShowGallery:null,
    },
    getters:{   //處理state中的數(shù)據(jù) 類似過濾器的作用;
        getImgurl(state){
            return state.imgUrl
        },
        getBool(state){
            return state.isShowGallery
        }

    },
    //分發(fā)狀態(tài) 改變state.imgUrl原先的值
    mutations:{
        setImg:function(state,data){
            state.imgUrl = data[0];
            state.isShowGallery=data[1];
        }
    },
    //action觸發(fā)
    actions:{
        setImg(context,data){
            context.commit("setImg",data)
        }
    }
});

var vue = new Vue({
    el: "#demo",
    template: `
        <div>
            <xlist></xlist>
            <xgallery></xgallery>
        </div>
        `,
        store//第一步將Soter注入構造器中;  這個一定要寫
})
</script>

上傳數(shù)據(jù)部分

<xlist>
    methods:{
        setImg(imgUrl){
           this.$store.dispatch('setImg',[imgUrl,true])
         }
    }
</xlist>

接收數(shù)據(jù)部分

<xgallery>
    computed:{
            isShowGallery(){
                return this.$store.getters.getBool
            },
            imgUrl(){
                return this.$store.getters.getImgurl
            }
    }
 //  數(shù)據(jù)顯示 => {{imgUrl}}  / {{isShowGallery}}
</xgallery>

路由

標準寫法

<script>
        //1.1定義但是沒注冊
        var page1 = {
            template: `
                <div>第一頁</div>
            `
        }

        var page2 = {
            template: `
                <div>第二頁</div>
            `
        }
        //1.2注冊;
        var router = new VueRouter({
            routes: [{
                    path: '/index',
                    component: page1
                }, {
                    path: '/home',
                    component: page2
                },
                { 
                    path: '/', redirect: 'index'   //2重定向
                }]  
        })
        new Vue({
            el:"#app",
            router,// (縮寫)相當于 routes: routes
            template:`
                <router-view></router-view>
            `
        })
        //3.路由傳參數(shù);
    </script>

嵌套路由(三層)

<script>
    var router = new VueRouter({
        routes: [{
                path: '/index',
                component: {
                    template: `
                        <div>
                            這是index的頁面
                            <a href="#/index/a">a</a>
                            <a href="#/index/b">b</a>
                            <router-view></router-view>
                        </div>
                    `
                },
                children: [{
                    //子路由沒有/
                    path: 'a',
                    component: {
                        template: `
                            <div>
                                <p>a</p>
                                <a href="#/index/a/aa">aa</a>
                                <a href="#/index/a/bb">bb</a>
                                <router-view></router-view>
                            </div>
                        `
                    },
                    children: [{
                        path: 'aa',
                        component: {
                            template: "<p>aa</p>"
                        }
                    }, {
                        path: 'bb',
                        component: {
                            template: "<p>bb</p>"
                        }
                    }]
                }, {
                    //子路由沒有/
                    path: 'b',
                    component: {
                        template: "<p>b</p>"
                    }
                }]
            }, {
                path: '/detail',
                component: {
                    template: `
                        <div>
                            這是detail的頁面
                        </div>
                    `
                }
            }, {
                path: '/',
                redirect: '/index'
            }]
            // (縮寫)相當于 routes: routes
        });
        new Vue({
        el: "#demo",
        template: `
            <div>
                <a href="#/index">index</a>
                <a href="#/detail">detail</a>
                <router-view></router-view>
            </div>
        `,
        router,
        mounted() {
            console.log(this)
        }
    })
</script>

補充:

定義全局屬性與方法

/*
    // 一個頁面用一個構造器即可;不建議用多個構造器;  
    //可以將構造器理解為一個組件;組件最大;  組件與組件之間的通信 ; 
     var(全局屬性) => angular中的$rootScope
     var  test(全局方法) => angular中的server;
*/
    var exchange = 1;
    var test = function(log){
        console.log(log)
    }
    //構造器 組件的一種呈現(xiàn)
    new Vue({
        //element節(jié)點 querySelector
        el:"#demo",
        //HTML CSS
        template:`
        <div>
            <p>{{name}} {{exchange}}</p>
            <button @click="test('abc')">Ok</button>
        </div>`,
        //需要綁定的數(shù)據(jù) $scope
        data:{
            name:"Hello",
            exchange
        },
        methods:{
            test
        }
    })

如何獲取$index索引值?

DEMO

<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div id="demo">
            <p v-for="(arr,index) in arrs" track-by="$index" :id="index">{{arr}}</p>
        </div>
    </body>
    <script src="../js/vue2.js"></script>
    <script>
        //構造器
        new Vue({
            //element節(jié)點 querySelector
            el:"#demo",
            //需要綁定的數(shù)據(jù) $scope
            data:{
                name:"Hello World",
                arrs:["a","b","c","a","d"]
            }
        })
    </script>
</html>

表單控件

DEMO

<html>

<head>
    <meta charset="UTF-8">
    <title></title>
</head>

<body>
    <!-- 雙向數(shù)據(jù)綁定而已; -->
    <div id="demo">
        <p style="color: red;">Radio</p>
        A:
        <input type="radio" value="A" v-model="radio" /> B:
        <input type="radio" value="B" v-model="radio" /> C:
        <input type="radio" value="C" v-model="radio" />
        <p>{{radio}}</p>
        <p style="color: red;">CheckBox</p>
        A:
        <input type="checkbox" value="A" v-model="checkbox" /> B:
        <input type="checkbox" value="B" v-model="checkbox" /> C:
        <input type="checkbox" value="C" v-model="checkbox" />
        <p>{{checkbox}}</p>
    </div>
</body>
<script src="../js/vue.js"></script>
<script>
//構造器
new Vue({
    //element節(jié)點 querySelector
    el: "#demo",
    //需要綁定的數(shù)據(jù) $scope
    data: {
        radio: "B",
        name: "Hello World",
        checkbox: ["A", "C"]
    }
})
</script>

</html>

render(高級玩法:可用來替換template)

<script>
new Vue({
    el: "#demo",
    data: {
        name: "laoyao"
    },
    //template: "<div>{{name}}</div>",
    render: function(createElement) {
        return createElement(
            //標簽
            'div', // tag name 標簽名稱
            {
                attrs: {
                    id: 'foo'
                },
            }, // 子組件中的陣列
            [createElement(
                'p',
                {
                    style:{
                        color: 'red',
                    }
                }
            ),["Hello"]]
        )
    },
})
</script>

過渡效果

內(nèi)置的組件transition

參考: 過渡:進入,離開和列表

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

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

  • Vue 實例 屬性和方法 每個 Vue 實例都會代理其 data 對象里所有的屬性:var data = { a:...
    云之外閱讀 2,373評論 0 6
  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,578評論 19 139
  • 1.安裝 可以簡單地在頁面引入Vue.js作為獨立版本,Vue即被注冊為全局變量,可以在頁面使用了。 如果希望搭建...
    Awey閱讀 11,300評論 4 129
  • 這篇筆記主要包含 Vue 2 不同于 Vue 1 或者特有的內(nèi)容,還有我對于 Vue 1.0 印象不深的內(nèi)容。關于...
    云之外閱讀 5,178評論 0 29
  • 同步UDP客戶端 UDP是面向無連接的,使用起來比較簡單,打開socke之后,指定目標端口,直接進行接收和發(fā)送: ...
    長不胖的Garfield閱讀 2,771評論 0 1

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