vue series of articles (6) Computed Property computed

The expression in the template is very convenient, but They are primarily designed for simple operation. Putting too much logic in the template template will be too heavy and difficult to maintain. E.g:

<div id="example"> {{ message.split('').reverse().join('') }} </div>

In this place, the template is no longer a simple declarative logic. You have to look at some time to realize that this is flip the string you want to display the variable message. When you want to refer to flip the string here many times in the template, it will be more difficult to handle.

So, for any complex logic, you should use the calculation attribute.

 

For example, the original method will put the following methods method, each click dom objects, all methods in the method of execution would go, and put computed attributes, which is what execution Click for complex logic is optimized.

The following release our example.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Vue.js</title>
	<script src="https://cdn.jsdelivr.net/npm/vue"></script>
	<link rel="stylesheet" type="text/css" href="style.css">
	
</head>
<body>
	<div id="app">
		<h1>Computed计算属性</h1>
		<button v-on:click="a++">Add to A</button>
		<button v-on:click="b++">Add to B</button>
		<p>A - {{a}}</p>
		<p>B - {{b}}</p>
		<p>Age+A = {{addToA}}</p>
		<p>Age+B = {{addToB}}</p>
		
	<script type="text/javascript" src="app.js"></script>
</body>
</html>

app.js

new Vue({
	el: '#app',
	data: {
		age: 30,
		a: 0,
		b: 0
	},
	methods: {
		
	},
	computed: {
		addToA: function(){
			console.log("add to A");
			return this.a + this.age;
		},
		addToB: function(){
			console.log("add to B ");
			return this.b + this.age;
		}
	}
});

 

Guess you like

Origin blog.csdn.net/jsqfengbao/article/details/94740233