1.vue經常使用的修飾符,number,trim,number--->看成數字,trim-->去掉先後空格vue
2.methods與計算屬性 computed 的相同與區別node
1 <body> 2 <div id="app"> 3 {{getInfo()}} 4 {{getInfo1}} 5 </div> 6 <script src="./node_modules/vue/dist/vue.js"></script> 7 <script> 8 let vm = new Vue({ 9 data:{ 10 foo: "hello ", 11 bar: "world" 12 }, 13 // 方法不會緩存 在模板中調用須要用getInfo() 14 methods: { 15 getInfo() { 16 console.log("getInfo is called"); 17 return this.foo + this.bar; 18 } 19 }, 20 // 計算屬性 本質上是一個方法 使用時候看成屬性來用 21 /* 計算屬性具備緩存 只有當其依賴的數據成員發生改變時候 才從新執行*/ 22 computed: { // Obejct.defineProperty() 23 getInfo1() { 24 console.log("getInfo1 is called"); 25 return this.foo + this.bar; 26 } 27 } 28 }).$mount("#app"); 29 30 /*輸出 31 getInfo is called 32 getInfo1 is called 33 */ 34 </script> 35 </body
總結:computed本質上是一個方法,使用的時候看成屬性來用,計算屬性具備緩存 只有當其依賴的數據成員發生改變時候 才從新執行,方法不會緩存,看成方法去調用。緩存
3.watch vs computedapp
<body> <div id="app"> {{getInfo1}} {{getInfo}} </div> <script src="./node_modules/vue/dist/vue.js"></script> <script> let vm = new Vue({ data:{ foo: "hello ", bar: "world", getInfo:"" }, // 計算屬性 本質上是一個方法 使用時候看成屬性來用 /* 計算屬性具備緩存 只有當其依賴的數據成員發生改變時候 才從新執行*/ computed: { // Obejct.defineProperty() getInfo1() { console.log("getInfo1 is called"); return this.foo + this.bar; } }, // watch vs computed // 1 儘可能優先使用computed 代碼簡潔 // 2 watch支持異步 watch: { /* foo(newValue,oldValue) { this.getInfo = this.foo + this.bar; }, bar(newValue,oldValue) { this.getInfo = this.foo + this.bar; }*/ foo:{ handler() { setTimeout(()=>{ this.getInfo = this.foo + this.bar; },1000); }, immediate: true //當即執行,爲false的時候第一次渲染不會出來,只有當數據改變的時候纔會變 }, bar() { this.getInfo = this.foo + this.bar; } } }).$mount("#app"); </script> </body>
總結:1 儘可能優先使用computed 代碼簡潔 異步
2 watch支持異步this