Loading

06计算属性computed使用

 1 <!doctype html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <meta name="viewport"
 6           content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
 7     <meta http-equiv="X-UA-Compatible" content="ie=edge">
 8     <title>06计算属性computed使用</title>
 9     <script src="https://cdn.bootcdn.net/ajax/libs/vue/3.2.40/vue.global.prod.js"></script>
10 </head>
11 <body>
12 <div id = "app">
13     <!--计算属性-->
14     <button @click="desc()">减少</button>{{num}}<button @click="add()">增加</button>
15     <!--响应式数据-->
16     <div style="background-color: red;color: white">响应式数据: {{compute}}</div>
17     <div style="background-color: red;color: white" v-if="error">提示: {{error}}</div>
18 </div>
19 
20 <script>
21     let app = Vue.createApp({
22         data() {
23             return {
24                 num: 1,
25             };
26         },
27         // 计算属性的特点是可以使用响应式数据(计算属性的调用方式跟data中属性的调用的方式是一样的)
28         computed: {
29             compute() {
30                 return this.num;
31             },
32             error() {
33                 return this.num === 0 ? '不能小于0' : this.num === 10 ? '不能超过10' : ''
34             },
35         },
36         methods:{
37             add(){
38                 // this表示当前的组件(当前是根组件,即下面的vm)
39                 if (this.num < 10) this.num++;
40             },
41             desc() {
42                 if (this.num > 0) this.num--;
43             },
44         },
45     });
46 
47     let vm = app.mount('#app');
48 </script>
49 </body>
50 </html>

 

posted @ 2022-10-15 14:40  云起时。  阅读(23)  评论(0编辑  收藏  举报