計(jì)算屬性(computed)钓觉,主要用于處理一些復(fù)雜邏輯。
基礎(chǔ)例子
<div id="app">
<p>原始字符串: {{ message }}</p>
<p>計(jì)算后反轉(zhuǎn)字符串: {{ reversedMessage }}</p>
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
message: 'Runoob!'
},
computed: {
// 計(jì)算屬性的 getter
reversedMessage: function () {
// `this` 指向 vm 實(shí)例
return this.message.split('').reverse().join('')
}
}
})
</script>
computed vs methods
我們可以使用 methods 來替代 computed讹堤,效果上兩個(gè)都是一樣的歇攻,但是 computed 是基于它的依賴緩存粗恢,只有相關(guān)依賴發(fā)生改變時(shí)才會(huì)重新取值。而使用 methods 片酝,在重新渲染的時(shí)候囚衔,函數(shù)總會(huì)重新調(diào)用執(zhí)行。使用 computed 性能會(huì)更好雕沿,但是如果你不希望緩存练湿,可以使用 methods 屬性藐守。
例1:購(gòu)物車價(jià)格計(jì)算
<!DOCTYPE html>
<html class="no-js">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>vue.js computed練習(xí)-計(jì)算購(gòu)物車總價(jià)</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<style type="text/css">
.container {
display: felx;
width: 370px;
margin: 0 auto;
flex-direction: column;
}
.item {
display: flex;
border: 1px solid #000;
border-radius: 10px;
width: 350px;
height: 50px;
margin-bottom: 10px;
/* 垂直方向居中 */
align-items: center;
/* 水平方向居中 */
/* justify-content: center; */
padding-left: 10px;
padding-right: 10px;
}
.item-id {
flex: 1 1 15%;
}
.item-cover {
flex: 1 1 10%;
}
.item-name {
flex: 1 1 30%;
}
.item-price {
flex: 1 1 20%;
}
.item-count {
flex: 1 1 25%;
}
.goods-count {
width: 20px;
}
.totalPrice {
display: flex;
width: 370px;
justify-content: space-between;
align-items: center;
}
.btn-settle {
width: 100px;
height: 30px;
background-color: #87CEEB;
border-radius: 5px;
border: none;
outline: none;
color: #FFF;
font-size: 16px;
}
</style>
</head>
<body>
<div id="app">
<div class="container">
<div class="item" v-for="goods in goodsList">
<div class="item-id">
{{goods.id}}
</div>
<div class="item-cover">
<a v-bind:href="goods.url" target="_blank"><img :src="goods.cover" width = "35"/></a>
</div>
<div class="item-name">
{{goods.name}}
</div>
<div class="item-price">
{{goods.price}}
</div>
<div class="item-count">
<button type="button" @click="goods.count -= 1" :disabled="goods.count === 0 || settled">-</button>
<input type="text" class="goods-count" v-model="goods.count" />
<button type="button" @click="goods.count += 1" :disabled="settled">+</button>
</div>
</div>
<div class="totalPrice">
<h3>Total Price</h3>
<p>¥{{totalPrice}}</p>
<button type="button" class="btn-settle" @click="settle" :disabled="settled">結(jié)算</button>
</div>
<div class="price" v-if="settled">
<p>您購(gòu)買了{(lán){totalCount}}件商品廊镜,需要支付總價(jià)為:{{totalPrice}}</p>
</div>
</div>
</div>
<script type="text/javascript">
var app = new Vue({
el: '#app',
data: {
goodsList: [
{
id : 1,
name : 'iPhone 8',
price : 3999,
url: "https://item.jd.com/5089267.html",
cover: "https://ss2.baidu.com/6ONYsjip0QIZ8tyhnq/it/u=3841252853,949538163&fm=58",
count : 1,
},
{
id : 2,
name : 'iPhone X',
price : 6349,
url: "https://item.jd.com/5089253.html",
cover: "https://ss2.baidu.com/6ONYsjip0QIZ8tyhnq/it/u=3159575759,329221210&fm=58",
count : 1,
},
{
id : 3,
name : 'iPhone Xs',
url: "https://item.jd.com/100000177748.html",
cover: "http://2c.zol-img.com.cn/product_small/13_120x90/816/cenfNF9Ndm2Y.jpg",
price : 7899,
count : 1,
},
],
settled: false,
},
methods: {
settle:function() {
this.settled = true;
}
},
computed: {
totalPrice:function() {
var totalPrice = 0;
for(var i = 0; i < this.goodsList.length; i ++) {
totalPrice += this.goodsList[i].price * this.goodsList[i].count;
}
return totalPrice;
},
totalCount:function() {
var totalCount = 0;
for(var i = 0; i < this.goodsList.length; i ++) {
totalCount += this.goodsList[i].count;
}
return totalCount;
}
},
})
</script>
</body>
</html>
例2:搜索頁(yè)面
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Vue.js computed練習(xí)-搜索頁(yè)面的實(shí)現(xiàn)</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<style type="text/css">
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
a {
text-decoration: none;
color: #333;
}
.container {
width: 95%;
margin: 0 auto;
}
.input {
display: flex;
width: 100%;
margin: 0 auto;
flex-direction: row;
margin-top: 10px;
margin-bottom: 20px;
}
.input-box {
flex: 1 1 70%;
margin-right: 5%;
border-radius: 5px;
border: 1px solid #eee;
}
.search-btn {
flex: 1 1 30%;
height: 30px;
background-color: #87CEEB;
border-radius: 5px;
border: none;
outline: none;
color: #FFF;
font-size: 16px;
}
.item {
display: flex;
border: 1px solid #eee;
border-radius: 8px;
margin-bottom: 8px;
height: 100%;
}
.item-text {
flex: 1 1 65%;
margin: 8px;
}
.item-title {
font-size: 18px;
font-weight: bold;
}
.item-content {
color: #B4B4B4;
font-size: 15px;
}
.item-thumbnail {
flex: 1 1 35%;
margin: 15px;
display: table-cell;
text-align: center;
vertical-align: middle;
}
.item-thumbnail img {
max-width: 100%;
height: 100px;
}
</style>
</head>
<body>
<div id="app">
<div class="container">
<div class="input">
<input type="text" v-model="searchString" placeholder=" 請(qǐng)輸入" class="input-box" />
<button type="button" class="search-btn" @click="search">搜索</button>
</div>
<div v-if="flag">
<div class="item" v-for="article in filteredArticles">
<div class="item-text">
<p class="item-title"><a :href="article.url" target="_blank">{{article.title}}</a></p>
<p class="item-content">{{article.content}}</p>
</div>
<div class="item-thumbnail">
<img :src="article.image">
</div>
</div>
</div>
<div v-else>
<div class="item" v-for="article in articles">
<div class="item-text">
<p class="item-title"><a :href="article.url" target="_blank">{{article.title}}</a></p>
<p class="item-content">{{article.content}}</p>
</div>
<div class="item-thumbnail">
<img :src="article.image">
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
var app = new Vue({
el: '#app',
data: {
searchString: "",
// 數(shù)據(jù)模型
articles: [{
"title": "堪稱神器的3款在線工具,你一定用得上脾猛!",
"url": "http://www.reibang.com/p/e83e7999346b",
"image": "https://upload-images.jianshu.io/upload_images/11438996-56b25f32c9307b4b?imageMogr2/auto-orient/strip%7CimageView2/2/w/640/format/webp",
"content": "一款在線免費(fèi)GIF編輯神器,提供在線GIF壓縮贤姆、視頻轉(zhuǎn)GIF榆苞、GIF合成、GIF裁剪四個(gè)功能霞捡,用戶無需安裝任何插件就可以輕松的進(jìn)行視頻格式...",
},
{
"title": "經(jīng)典面試題:從 URL 輸入到頁(yè)面展現(xiàn)到底發(fā)生什么坐漏?",
"url": "http://www.reibang.com/p/45ba3e0d0c7e",
"image": "https://upload-images.jianshu.io/upload_images/3973862-d90954249a6f6ccd.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1000/format/webp",
"content": "打開瀏覽器從輸入網(wǎng)址到網(wǎng)頁(yè)呈現(xiàn)在大家面前,背后到底發(fā)生了什么碧信?經(jīng)歷怎么樣的一個(gè)過程赊琳?先給大家來張總體流程圖,具體步驟請(qǐng)看下文分..."
},
{
"title": "如何免翻墻使用谷歌搜索和Chrome應(yīng)用商店",
"url": "http://www.reibang.com/p/484f8e6c88f6",
"image": "https://upload-images.jianshu.io/upload_images/858154-015a4b083685a3d1.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/800/format/webp",
"content": "可能大家都聽過或正在使用谷歌瀏覽器砰碴,但是由于某種原因只能在谷歌瀏覽器使用百度搜索引擎躏筏,至于什么谷歌搜索引擎、谷歌商城呈枉、Gmail郵箱..."
},
{
"title": "四款前所未有好用的黑科技APP趁尼,絕對(duì)的良心實(shí)用,趕緊告訴家人",
"url": "http://www.reibang.com/p/2aec84d269fe",
"image": "https://upload-images.jianshu.io/upload_images/16042993-168b2cb17fd7ec0c?imageMogr2/auto-orient/strip%7CimageView2/2/w/640/format/webp",
"content": "手機(jī)微信猖辫、支付寶酥泞、淘寶等應(yīng)用都是我們經(jīng)常會(huì)使用到的APP,除此之外啃憎,我們就來就給大家?guī)韼卓罡佑腥ず猛娴暮诳萍糀PP芝囤,絕對(duì)的良心實(shí)用..."
},
{
"title": "堅(jiān)持學(xué)英語的方法有哪些",
"url": "http://www.reibang.com/p/0a6a61b0933c",
"image": "https://upload-images.jianshu.io/upload_images/3525704-c7293758fc59e56b.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/960/format/webp",
"content": "學(xué)習(xí)英語沒有什么捷徑,至少我認(rèn)為辛萍,我一直以來都是自學(xué)英語悯姊,從沒有聽過課堂上老師是怎么講英語的,都是通過聽廣播和看視頻學(xué)會(huì)的叹阔。我想說..."
}
],
flag : false,
},
methods: {
search: function() {
this.flag =! this.flag;
}
},
computed: {
// 計(jì)算函數(shù)挠轴,匹配搜索
filteredArticles: function() {
var articles_array = this.articles,
searchString = this.searchString;
//搜索關(guān)鍵詞為空,則返回原始數(shù)據(jù)集
if (!searchString) {
return articles_array;
}
//搜索關(guān)鍵詞去除無用空格,轉(zhuǎn)換為小寫
searchString = searchString.trim().toLowerCase();
//過濾數(shù)組中每個(gè)元素,如果
articles_array = articles_array.filter(function(item) {
if (item.title.toLowerCase().indexOf(searchString) !== -1 ) {
return item;
}
})
// 返回轉(zhuǎn)化后的數(shù)組
return articles_array;
},
}
})
</script>
</body>
</html>