1. 程式人生 > >vue與react關係和Angular的區別

vue與react關係和Angular的區別

一、為什麼學習vue.js

vue.js兼具angular.js和react的優點,並且剔除了他們的缺點

官網:http://cn.vuejs.org/

手冊:http://cn.vuejs.org/v2/api/

二、vue.js是什麼

Vue是一個"MVVM框架(庫)",和angular類似,相比angular小巧,比較容易上手

Vue是一個構建使用者介面點的漸進式框架,與其他重量級框架不同的是,vue採用自底向上增量開發的設計

vue的核心庫"只關注檢視層",並且"非常容易學習",非常容易與其他庫或者已有的專案整合,另一方面,vue完全有能力驅動採用單檔案元件和vue生態系統支援的庫開發的複雜單頁面應用

vue的目標是通過儘可能簡單的API實現"響應的資料繫結"和"組合的檢視元件"

三、MVC/MVP/MVVM的區別

複雜的軟體必須有清晰合理的架構,否則無法開發和維護

MVC、MVP和MVVM否是用來解決介面呈現和邏輯程式碼分離而出現的模式

通俗的講:就是方便大多數人開發和維護出現的程式碼分離模式

課外拓展:http://www.cnblogs.com/lori/p/3501764.html

四、MVC

檢視(view):使用者介面

控制器(controller):業務邏輯

模型(Model):資料處理

五、MVP

MVP 是從經典的模式MVC演變而來,它們的基本思想有相通的地方:Controller/Presenter負責邏輯的處理,Model提供資料,View負 責顯示。作為一種新的模式,MVP與MVC有著一個重大的區別:在MVP中View並不直接使用Model,它們之間的通訊是通過Presenter (MVC中的Controller)來進行的,所有的互動都發生在Presenter內部,而在MVC中View會從直接Model中讀取資料而不是通過 Controller。

六、MVVM

MVVM在概念上是真正將頁面與資料邏輯分離的模式,在開發方式上,它是真正將前臺程式碼開發者(JS+HTML)與後臺程式碼開發者分離的模式(asp,asp.net,php,jsp)

雙向繫結:view的變動,自動反映在viewModel,反之亦然

七、vue對比其他框架

1、vue-angular

1)、vue在設計之初參考了很多angular的思想

2)、vue相比於angular來說更加的簡單

3)、vue相當於angular要變得小巧很多,執行速度比angular快

4)、vue和angular繫結都可以用{{}}

5)、vue指令用v-xxx,angular用ng-xxx

6)、vue中資料放在data物件裡面,angular資料繫結在$scope上面

7)、vue有元件化概念,angular中沒有

2、vue-react

他們都有:

1)、react和vue都是用虛擬DOM Virtual DOM

2)、React和Vue都提供了響應式(Reactive)和元件化(Componsable)的檢視元件

3)、React和vue都將注意力集中保持在核心庫,伴隨於此,有配套的路由和負責處理全域性狀態管理的庫

4)、React使用JSX渲染頁面,Vue使用簡單的模板

5)、Vue比react執行更快

八、初始vuejs

1)、下載vuejs的生產版本

下載地址:http://cn.vuejs.org/v2/guide/installation.html

2)、例項化一個Vue物件

var vm = new Vue({

  // 選項

})

3)、在頁面中div#box

4)、修改配置選項

複製程式碼

var vw = new Vue({

el:"#box",//選擇元素

data:{//定義資料

msg:"這裡是Vue",

name:"vue"

 

}

})

複製程式碼

5)、迴圈資料:傳入陣列,物件,使用v-for來進行迴圈遍歷資料

複製程式碼

list:[1,2,4]

<li v-for="item in list">{{item}}</li>

 

list1:[{

name:"張三",

age:30

},

{

name:"李四",

age:30

},{

name:"王五",

age:30

}]

<li v-for="item in list1">

{{item.name}}/{{item.age}}

</li>

複製程式碼

6)、方法事件

所有的方法都配置於methods選項中

複製程式碼

methods:{//放置方法,訪問data中的資料,可以直接使用this訪問,執行通過v-on來訪問,也可以使用簡寫的形式@click來執行方法

getName:function(){

alert(this.name)

},

run:function(){

alert("這是run方法");

}

}

<div v-on:click="getName()">執行getName方法</div>

<br />

<div  @click="run()">執行run方法</div>

複製程式碼

7)、雙向的資料繫結

<input type="text" v-model="name" />

{{name}}

8)、使用jquery實現todolist

a)引入bootstrap

b)繫結事件

新增資料使用append

刪除事件使用remove

9)、使用vue實現todolist

a)引入bootstrap.css,編輯介面

b)例項化vue.js

複製程式碼

data:{

info:""//輸入框的值

list:[]//資料列表,迴圈資料使用v-for,因為需要涉及到刪除功能,所以需要遍歷的時候將索引值也傳遞進去(item,key) in list

},

methods:{

addData:function(){//可以傳值

this.list.push(this.info)

console.log(this.info)

},

deleteData:function(key){

this.list.splice(key,1)

}

}

<tr v-for="(item,key) in list">

            <td>{{item}}</td>

            <td><button type="button" class="btn btn-danger " @click="deleteData(key)">刪除</button></td>

        </tr>

複製程式碼

1)文字繫結

v-text指令

<span v-text="name"></span>   相當於angularjs中的ng-bind

給data中新增:test:"<strong>你會解析嗎</strong>",

如果使用{{test}}則會直接顯示出所有的程式碼,不會解析

如果使用<span v-text="test"></span> 則會直接顯示出所有的程式碼,不會解析

我們可以使用v-html來解析程式碼

<span v-html="test"></span>

2)繫結屬性

data中新增一個id:"這是一個id"

<div v-bind:id="id">新增屬性</div>

這裡需要注意不要加{{}}  跟angular中的ng-src等屬性一樣

簡寫形式

複製程式碼

<div :id="id">新增屬性</div>

 

url:"https://www.baidu.com/img/bd_logo1.png"

<img :src="url"/>

複製程式碼

3)事件

複習todolist

事件物件,注意將$event傳入方法中

複製程式碼

<button data-id="1638" data-user="wxx" @click="requestData($event)">事件物件</button>

requestData:function(event){

console.log(event)

}

複製程式碼

資料在srcElement中的dataset中

4)表示式

複製程式碼

data:{number:200}

{{number+200}}

data:{ok:true}

{{ok:"是":"否"}}

data:{msg:"倒序輸出該欄位"}

{{msg.split("").reverse().join("")}}

複製程式碼

5)、計算屬性--輸入提示---autocomplete(表單屬性)

複製程式碼

computed:{

c:function(){

return this.a + 6;

},

reverseMsg:function(){

return this.message.split("").reverse().join("");

}

}

c={{c}}

<br />

msg={{reverseMsg}}

複製程式碼

注意,當message改變之後,會重新計算並且改變檢視,寫一個按鈕來執行改變message為"改變了message"

案例

data中

search:"",

searchList:["appale","pear","banner","orange"],

cumputed

<input type="text"  v-model="search"/>

<p v-for="item in searchList">{{item}}</p>

新增計算屬性

複製程式碼

listSearch:function(){

var arr = [];

var that = this;

this.searchList.forEach(function(val){

if(val.indexOf(that.search)!=-1){

arr.push(val);

}

})

return arr;

}

複製程式碼

更改迴圈條件為

<p v-for="item in listSearch">{{item}}</p>

6)監聽資料變化  watch

複製程式碼

// vm.$watch(vm)    vm.msg 拿到 vue上面data繫結的資料

        /*注意監聽文字框改變的時候 這裡直接寫data上面繫結的值*/

         <input type="text" v-model='msg'>

          data:{

                msg:'我是一個數據'

            }

            

         vm.$watch('msg',function(newValue,oldValue){

 

            console.log(newValue+'-------'+oldValue);

 

 

        })

        

                       第二種寫法

             data:{

               msg:'我是一個數據'

            },

            watch:{

 

                msg:function(newValue,oldValue){

 

                    console.log(newValue+'-------'+oldValue);

                }

            }

複製程式碼

7)計算屬性和方法的對比

案例:翻轉字串----多次呼叫

//計算屬性只有在它的相關依賴發生改變時才會重新取值。這就意味著只要 message 沒有發生改變,多次訪問 reversedMessage 計算屬性會立即返回之前的計算結果,而不必再次執行函式。

    //總結:計算屬性比方法的效率更高

    8)計算屬性和watch對比

    Vue.js 提供了一個方法 $watch ,它用於觀察 Vue 例項上的資料變動。當一些資料需要根據其它資料變化時, $watch 很誘人 —— 特別是如果你來自 AngularJS 。不過,通常更好的辦法是使用計算屬性而不是一個命令式的 $watch 回撥。思考下面例子:

複製程式碼

<input type="text" v-model="firstName">

        <input type="text" v-model="lastName">

       {{fullName}}

       watch: {

          firstName:function(val){

              this.fullName=val+this.lastName;

          },

          lastName:function(val){

              this.fullName=this.firstName+val;

          }

      }

複製程式碼

          9)計算屬性實現

複製程式碼

computed: {

        fullName: function () {

            return this.firstName + ' ' + this.lastName

        }

      }

10)class語法

.static{

            width: 200px;

            height: 200px;

        }

        .class-a{

            width: 200px;

            height: 200px;

            background: orange;

        }

        .class-b{

            background: blue;

        }

<div class="static" :class="{ 'class-a': isA, 'class-b': isB }">

            v-bind-class111

        </div>

        <br>

        <div :class="classObject">classObject</div>

複製程式碼

//    可以傳給 v-bind:class 一個物件,以動態地切換class。注意 v-bind:class 指令可以與普通的 class 特性共存。

複製程式碼

var vm = new Vue({

    el: '#demo',    //div   .class

    data: {

        isA: true,

        isB: false,

        classObject: {

            active: true,

            'class-a': true

        }

 

    }

})

複製程式碼

11)style語法

複製程式碼

//v-bind:style的物件語法十分直觀——看著非常像 CSS,其實它是一個JavaScript物件。CSS屬性名可以用駝峰式(camelCase)或短橫分隔命名(kebab-case)

<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }">Style 物件語法</div>

  data: {

            activeColor: 'red',

            fontSize: 30

        }

複製程式碼

    12)style陣列

複製程式碼

 <div v-bind:style="[styleObjectA, styleObjectB]">Style 陣列語法</div>

     data: {

            styleObjectA: {

                color: 'red'

            },

            styleObjectB: {

                fontSize: '30px'

            }

        }

複製程式碼

    13)v-if---dom操作

複製程式碼

 v-else

    v-show--顯示隱藏

    <h1 v-if="ok">這是一個h1</h1>

      <h1 v-show="ok">這是一個h1</h1>

       <div v-if="Math.random()>0.5">

                    大於0.5

        </div>

        <div v-else>

                  小於0.5

        </div>

     data: {

            ok:true

        }

複製程式碼

    14、迴圈的使用

    多層迴圈

    可以使用in  也可以使用of

    15、   過濾器

複製程式碼

Vue.filter('reverseMsg',function(value){

                return value.split('').reverse().join('');

            });

            Vue.filter('toDou',function(value,n1,n2){

               console.log(value+'--'+n1+'--'+n2);

                if(n1>n2){

                    return 123;

                }else{

                    return 456;

                }

            })

data:{

                msg:'我是程式碼搬磚工',

                num:'123'

            }

         {{msg}}

        {{msg | reverseMsg}}

        {{num}}

        {{num | toDou(12,14)}}

複製程式碼

    16)、ajax請求

    axios:http://blog.csdn.net/liaoxiaojuan233/article/details/54176798

    fetch:https://segmentfault.com/a/1190000003810652

複製程式碼

// 1.  應用fetch或axios 獲取資料

     <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

     axios.get(url)

           .then(function (response) {

               console.log(response.data.result);

 

               _that.list=response.data.result;

           })

           .catch(function (error) {

               console.log(error);

           });

        //2. https://github.com/pagekit/vue-resource

         <script src="https://cdn.jsdelivr.net/vue.resource/1.0.3/vue-resource.min.js"></script>

         //第二個引數如果返回資料為callback時可以不設定

          this.$http.jsonp(api,{

             jsonp:'cb'//如果介面為不為callback,為cb時,修改此引數,例如https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=php

         }).then(function(data){

             console.log(data.body);

             that.list=data.body.s;

          },function(){

          })

複製程式碼