computed vs methods
我们可以使用 methods 来替代 computed,效果上两个都是一样的,但是 computed 是基于它的依赖缓存,只有相关依赖发生改变时才会重新取值。而使用 methods ,在重新渲染的时候,函数总会重新调用执行。
理解如下:computed 如果在使用缓存的时候性能会高于methods.不考虑缓存,则二者一样。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 循环语句 </title>
<script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>
<style>
table {
border: 1px solid black;
}
table {
width: 100%;
}
th {
height: 50px;
}
th,
td {
border-bottom: 1px solid #ddd;
}
</style>
</head>
<body>
<div id="example">
<p>原始字符串: {{ message }}</p>
<p>计算后反转字符串: {{ reversedMessage }}</p>
<p>使用方法后反转字符串(如果是方法要记得加括号): {{ reversedMessage2() }}</p>
</div>
<div>
<p>终于开始看到框架的优越性了</p>
</div>
<div id="app">
<table>
<tr>
<th>序号</th>
<th>商品名称</th>
<th>商品价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
<tr v-for="iphone in Ip_Json">
<td>{{ iphone.id }}</td>
<td>{{ iphone.name }}</td>
<td>{{ iphone.price }}</td>
<td>
<button @click="iphone.count-=1">-</button>
{{ iphone.count }}
<button @click="iphone.count+=1">+</button>
</td>
<td>
<button v-on:click="iphone.count=0">移除</button>
</td>
</tr>
</table>
总价:${{ totalPrice() }}
</div>
<div>
<div>
<p>参数传递</p>
</div>
<div id="parms">
<button v-on:click="say('hi',$event)">say hi</button>
</div>
</div>
<script>
var vm = new Vue({
el: '#example',
data: {
message: 'Hello'
},
computed: {
// a computed getter
reversedMessage: function() {
// `this` points to the vm instance
return this.message.split('').reverse().join('') + ' ' + getNowDate();
}
},
methods: {
reversedMessage2: function() {
console.log(this.message);
return this.message.split('').reverse().join('') + ' ' + getNowDate();
}
}
})
var app = new Vue({
el: '#app',
data: {
Ip_Json: [{
id: 1,
name: 'iphone 8',
price: 5001,
count: 1
},
{
id: 2,
name: 'iphone xs',
price: 8001,
count: 1
},
{
id: 3,
name: 'iphone xr',
price: 6001,
count: 1
}
]
},
/* computed 和 methods 都可以,但是对应的totalPrice有是否带括号的区别 */
methods: {
totalPrice: function() {
var totalP = 0;
for (var i = 0, len = this.Ip_Json.length; i < len; i++) {
totalP += this.Ip_Json[i].price * this.Ip_Json[i].count;
}
alert(totalP);
console.log(totalP);
return totalP;
}
}
})
var parm = new Vue({
el: "#parms",
methods: {
say: function(p, e) {
console.log('传入参数=' + p);
console.log(e.currentTarget);
}
}
});
function getNowDate() {
var date = new Date(Date.now());
Y = date.getFullYear() + '-';
M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
D = date.getDate() + ' ';
h = date.getHours() + ':';
m = date.getMinutes() + ':';
s = date.getSeconds();
return Y + M + D + h + m + s;
}
</script>
</body>
</html>
其他的在这里: http://www.runoob.com/vue2/vue-events.html