<! DOCTYPE html><html lang="en">

<head>
	<meta charset="UTF-8">
	<title>Calculate attribute</title>
	<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>

<body>
	<div id="app">
		<! 1. Basic Usage -->
		<h2>MSG: {{MSG}}</h2>
		<h2>Msg2: {{msg2}}</h2>

		<! -->
		<h2>msg : {{msg.split(' ').reverse().join(' ')}}</h2>
		<h2>reverseMsg : {{reverseMsg}}</h2>
		<button @click="change">Modifying computing attributes</button>

		<! -- 2. Calculate attributes vs methods -->
		<h2>Num1: {{num1}}</h2>
		<h2>Num2 - Calculated attributes: {{num2}}</h2>
		<h2>{{getNum2()}}</h2>

		<! -- 3. Get and set -->
		<! - < h2 > {{num2}} < / h2 > < button @ click = "change2" > modify the computation attribute < / button > -- >


	</div>


	<script>
		var vm = new Vue({
			el: '#app'.data: { // Common attributes
				msg: 'welcome to itapp'.num1: 8
			},
			computed: { // Calculate attributes
				msg2: function () {
					// This function must have a return value to get the property, called the get function
					return 'hello';

				},
				reverseMsg() {
					return this.msg.split(' ').reverse().join(' ');
				},
				num2: {
					get() {
						console.log('num2:' + new Date());
						return this.num1 - 1;
					},
					set(val) {
						console.log('Modify num2');
						this.num1 = val; }}},methods: {
				change() {
					this.num2 = 50;
				},
				getNum2() {
					console.log(new Date());
					return this.num1 - 1; }},mounted() {
				// // Multiple retrieves calculated properties, which can be obtained from the cache to improve performance
				setInterval(function () {
					// console.log(vm.num2); // Fetch from cache
					console.log(vm.getNum2()); // Execute the function every time
				}, 1000); }});</script>
</body>

</html>
Copy the code