vue1與vue2的區別


參考鏈接:https://www.php.cn/js-tutorial-420232.html

1、生命周期函數

(1)vue1.0

周期 解釋
init 組件剛剛被創建,但Data、method等屬性還沒被計算出來
created 組件創建已經完成,但DOM還沒被生成出來
beforeCompile 模板編譯之前
compiled 模板編譯之后
ready 組件准備(平時用得較多)
attached 在 vm.$el 插入到DOM時調用
detached 在 vm.$el 從 DOM 中刪除時調用
beforeDestory 組件銷毀之前
destoryed 組件銷毀之后

  (2)vue2.0

周期 解釋
beforeCreate 組件剛剛被創建,但Data、method等屬性還沒被計算出來
created 組件創建已經完成,但DOM還沒被生成出來
beforeMount 模板編譯之前
mounted 模板編譯之后,組件准備
beforeUpdate 組件更新之前(數據等變動的時候)
updated 組件更新之后(數據等變動的時候)
activated for keep-alive,組件被激活時調用
deactivated for keep-alive,組件被移除時調用
beforeDestory 組件銷毀之前
destoryed 組件銷毀之后

2.0生命生命周期變化感覺變得更加語義化一點(有規律可尋,更好記了),而且增加了beforeUpdate、updated、activated、deactivated,刪除了attached、detached。

2、過濾器

(1)vue1.0

自帶過濾器。

定義方式:vue.filter('過濾器名字',fn) 

調用方式:{{msg | filterName'12' '5'}} 

(2)vue2.0

2.0移除了自帶過濾器,但是保留了自定義過濾器的功能。

定義方式:vue.filter('過濾器名字',fn) 

調用方式:{{msg | filterName('12','5')}}

以下是一個自定義過濾器示例:

Vue.filter('toDou',function(n,a,b){

    return n<10?n+a+b:''+n;

});

3、循環

關於整數循環,1.0的整數循環是從0開始的,2.0的整數循環是從1開始的,下面對比:

//HTML代碼
<ul id='box'>
    <li v-for='val in 5' v-text='val'>
    </li>
</ul>

4、代碼片段

編寫template的時候,2.0必須要用一個根元素(如div)將代碼片段包裹起來,否則報錯。

// 1.0

    <template>

        <h3>我是組件</h3><strong>我是加粗標簽</strong>

    </template>

// 2.0:  必須有根元素,包裹住所有的代碼

    <template id="aaa">

            <div>

                <h3>我是組件</h3>

                <strong>我是加粗標簽</strong>

            </div>

    </template>

5、組件定義

  (1)vue1.0

1)定義組件的方式:

Vue.extend            這種方式,在2.0里面有,但是有一些改動

Vue.component(組件名稱,{    在2.0繼續能用     

data(){

}     

methods:{

}    

template:

});

2)局部注冊

var Child = Vue.extend({ /* ... */ })
var Parent = Vue.extend({
  template: '...',
  components: {    // <my-component> will only be available in Parent's template
    'my-component': Child
  }
})

(2)vue2.0

1)定義組件的方式:

var Home={        template:''        ->   相當於Vue.extend()

};

2)局部注冊:

var Child = {  template: '<div>A custom component!</div>'}new Vue({  // ...
  components: {    // <my-component> 將只在父模板可用
    'my-component': Child
  }
})

6、給元素付唯一值

(1)vue 1.0 trace-by的方式

<div v-for="item in items" track-by="$index">

(2)vue 2.0 key的方式

<div v-for="item in items" :key="item.id">

7、自定義鍵盤指令

(1)vue1.0

  Vue.directive('on').keyCodes.f1=17

(2)vue2.0

  Vue.config.keyCodes.ctrl=17


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM