计算属性
1、基本使用
<div id="app"> <h2>{{getName()}}</h2> <!--计算属性--> <h2>{{fullName}}</h2> </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { message: 'hello', firstName: 'qi', lastName: 'jing' }, /*计算属性 */ computed: { fullName: function(){ return this.firstName+' ' + this.lastName } }, methods: { getName: function(){ return this.firstName+' '+this.lastName } } }) </script>
2、复杂使用
<div id="app"> <h2>总价格:{{totalPrice}}</h2> </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { message: 'hello', books: [ {id: 1, bookName:'深入计算机原理',price: 123}, {id: 2, bookName:'深入计算机原理',price: 124}, {id: 3, bookName:'深入计算机原理',price: 125}, {id: 4, bookName:'深入计算机原理',price: 126}, ] }, computed: { totalPrice: function (){ // let result = 0; // for(let i = 0;i<this.books.length;i++){ // result += this.books[i].price; // } // return result; return this.books.reduce((a,b)=>a+b.price,0) } } }) </script>
事件监听
1、基本使用
<div id="app"> <h2>{{count}}</h2> <button @click="increment()">+</button> <button @click="decrement()">-</button> </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { count: 0 }, methods: { increment() { this.count++; }, decrement() { this.count--; } } }) </script>
2、参数问题
<div id="app"> <button @click="btn01('abc')">按钮1</button> <!--在事件定义时,写方法省略了小括号,但是方法本身是需要一个参数的,VUE会默认 将浏览器生产的event事件对象作为参数传入方法中--> <button @click="btn02">按钮2</button> <!--方法定义时,既需要普通参数,又需要event参数时 $event--> <button @click="btn03('12121',$event)">按钮3</button> </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { message: 'hello' }, methods :{ btn01(str) { console.log('-----',str); }, btn02(str) { console.log(str); }, btn03(str,event) { console.log(str,event); } } }) </script>
3、修饰符
<!--1、.stop修饰符的使用--> <div id="app" @click="divClick()"> aaa <button @click.stop="btnClick()">按钮</button> <!--2、 prevent修饰符的使用--> <form action="baidu"> <input type="submit" value="提交" @click.prevent="submitClick" > </form> <!--3、监听某个按键--> <input type="text" @keyup.enter="keyUp"> <!--4、只让按钮在第一次有用--> <button type="button" @click.once="onceClick">按钮</button> </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { message: 'hello' }, methods: { divClick() { console.log('divClick'); }, btnClick() { console.log('btnClick'); }, submitClick() { console.log('submitClick'); }, keyUp() { console.log('keyUp'); }, onceClick() { console.log('onceClick'); } } }) </script>