1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8" />
- <meta http-equiv="X-UA-Compatible" content="IE=edge" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <title>Document</title>
- <script src="../../vue.js"></script>
- </head>
- <body>
- <div id="app">
- <!-- 第一种实现:通过插值语法中表达式 (只能完成简单的逻辑运算) -->
- <p>(1)我的姓名是:<b>{{ firstname + lastname }}</b></p>
- <!-- 第二种实现:通过vm方法 (简单或者复杂的逻辑都可以实现)-->
- <p>(2)我的姓名是:<b>{{ getFullname() }}</b></p>
- <!-- 第三种实现:通过Vue的计算属性:有缓存 -->
- <!-- 计算属性 定义时为方法;使用时为属性。 -->
- <!-- 计算属性,必须是同步任务,必须即刻有返回值。同时为了提高页面性能,尽量不要在计算属性里编写计算量大且耗时的代码 -->
- <p>(3)我的姓名是:<b>{{ fullname }}</b></p>
- <p>实际开发时,如何去使用计算属性?</p>
- <p>第一,尽量多的去使用计算属性(如果可以的话)</p>
- <p>
- 第二,如果需要再原有数据上生成新的数据(衍生数据),此时大概率是计算属性。
- </p>
- <p>
- 第三,如果计算属性中,需要编写异步或者耗时比较大的代码时,不要选择计算属性,可以通过监听器来实现
- </p>
- <p>(4)我的姓名是:<b>{{ full }}</b></p>
- </div>
- <script>
- var vm = new Vue({
- el: '#app',
- data: {
- firstname: '郭',
- lastname: '靖',
- full: '郭靖',
- },
- // 在参数对象中的watch里定义监听器
- watch: {
- firstname(newValue, oldValue) {
- // 所有监听器中 this 也是 Vue实例(vm)
- // 一旦 firstname 变化了,那么该监听器就会执行。同时接受两个参数,分为 新值 和 旧值。
- this.full = newValue + this.lastname;
- }, // 就是 firstname 监听器
- lastname(newValue, oldValue) {
- this.full = this.firstname + newValue;
- }, // 就是 lastname 监听器
- },
- // 在参数对象中的computed属性里定义计算属性,所有计算属性本质 都是 函数
- computed: {
- fullname() {
- // 所有计算属性 中 this 的值 都是 Vue实例(vm), 同时必须有返回值
- return this.firstname + this.lastname;
- },
- },
- methods: {
- getFullname() {
- // 在方法中,this 就是 Vue实例 (vm)
- return this.firstname + this.lastname;
- },
- },
- });
- </script>
- </body>
- </html>
|