![](https://i-blog.csdnimg.cn/blog_migrate/e334cd9300405d995ec0ef759d405b86.png)
封装函数是很好的方式,但有时重复的计算会消耗不必要的性能。
如何提高执行效率?
<div id="app">
<ul>
<!-- <li v-if="item>10" v-for="item in fn()">{{item}}</li> -->
<!-- <li v-for="item in fn()">{{item}}</li> -->
<li v-for="item in result">{{item}}</li>
</ul>
</div>
<script src="javascript/vue.js"></script>
<script>
var vm = new Vue({
el : '#app',
data:{
arr:[1,11,2,22,3,33,4,44]
},
methods: {
fn(){
var resArr = [];
for(var i = 0;i< this.arr.length ; i++) {
if(this.arr[i] > 10){
resArr.push(this.arr[i]);
}
}
return resArr;
}
},
computed:{
result(){
return this.arr.filter(item => item > 10)
}
}
})
<div id="app">
<p>{{ fullName }}</p>
</div>
<script src="lib/vue.js"></script>
<script>
var vm = new Vue({
el: '#app',
data: {
firstName: '张',
lastName: '三'
},
computed: {
// 默认书写方式:
/* fullName () {
return this.firstName + this.lastName;
} */
// 分开书写 getter 与 setter
fullName: {
get () {
return this.firstName + this.lastName;
},
set (newValue) {
console.log(newValue)
var nameArr = newValue.split(' ');
this.firstName = nameArr[0];
this.lastName = nameArr[1];
}
}
}
});