1. 程式人生 > 其它 >Vue 基礎2

Vue 基礎2

1. 計算屬性: 快取,

計算屬性會把第一次計算的結果存在到快取中,如果依賴的資料沒有發生變化,再次使用計算屬性時,會從快取中取上次計算的結果,這樣效能就提高。 使用場景:依賴的資料不經常發生變化時,使用計算屬性可以提高渲染效能. <script> var vm = new Vue({ el: "#app", data: { msg: "hello" }, // methods中定義是方法 methods: { sayHello(){ console.log("看看方法執行了幾遍?") //執行了兩遍 return this.msg; } }, // computed中定義計算屬性 computed: { // 計算屬性:本質也是一個函式。定義時和方法一樣。 getMsg(){ console.log("看看計算屬性執行了幾遍?") //執行了一遍 return this.msg; } } }) </script> 1.1 計算屬性 深入 (set,get)    <script> var vm = new Vue({ el: "#app", data: { firstName: '張', lastName: '三' }, computed:{ // 這種寫法,相當於只設置了get,所以只能獲取值,不能設定值。 // Computed property "fullName" was assigned to but it has no setter /* fullName(value){ return this.firstName + this.lastName } */
fullName: { // get()用來給計算屬性獲取值 get(){ return this.firstName + this.lastName; }, // set()用來給計算屬性設定值,引數是新值。 set(newValue){ // 新的全稱,需要拆開 this.firstName = newValue.charAt(0) this.lastName = newValue.slice(1) } } } }) </script>