vue 计算属性

<template>
  <p>Has published books:</p>
  <span>{{ author.books.length > 0 ? 'Yes' : 'No' }}</span>
  <span>{{ author.books.length > 0 ? 'Yes' : 'No' }}</span>
  <span>{{ author.books.length > 0 ? 'Yes' : 'No' }}</span>

  <p>methods:Has published books:</p>
  <span>{{ publishedBooksMessageMethod() }}</span>
  <span>{{ publishedBooksMessageMethod() }}</span>
  <span>{{ publishedBooksMessageMethod() }}</span>
  <button @click="publishedBooksMessageMethod">按钮事件测试</button>



  <p>computed:Has published books:</p>
  <span>{{ publishedBooksMessage }}</span>
  <span>{{ publishedBooksMessage }}</span>
  <span>{{ publishedBooksMessage }}</span>
  <p>computed:date</p>
  <span>{{ now }}</span>
  <span>{{ now }}</span>
  <span>{{ now }} </span>

  <div>
    <button @click="author.books.push('vue - text')">修改书单</button>

  </div>
  <div>
    <button @click="publishedBooksMessage = 'text'">添加书单-set</button>
  </div>
</template>
<script>
export default {
  data() {
    return {
      author: {
        name: 'John Doe',
        books: [
          'Vue 2 - Advanced Guide',
          'Vue 3 - Basic Guide',
          'Vue 4 - The Mystery'
        ]
      }
    }
  },
  // 计算属性值会基于其响应式依赖被缓存。一个计算属性仅会在其响应式依赖更新时才重新计算。
  computed: {
    // // 一个计算属性的 getter 简写
    // publishedBooksMessage() {
    //   console.log('computed');
    //   // `this` 指向当前组件实例
    //   return this.author.books.length > 0 ? 'Yes' : 'No'
    // },
    // 完整写法
    publishedBooksMessage: {
      // 计算属性一般没有set方法
      set: function (newValue) {
        console.log(newValue);
        console.log(this.author.books);
        console.log(this.author.books.length)

        this.author.books.push(newValue)
        console.log(this.author.books);
        console.log(this.author.books.length)


      },
      get: function () {
        console.log('computed');
        console.log(this.author.books.length)
        return this.author.books.length > 0 ? 'Yes' : 'No'
      }
    },
    now() {
      return Date.now()
    }

  },
  // 方法调用总是会在重渲染发生时再次执行函数
  methods: {
    publishedBooksMessageMethod() {
      console.log('methods');
      // `this` 指向当前组件实例
      return this.author.books.length > 0 ? 'Yes' : 'No'
    },
    pushBook: function () {
      console.log(this.author.books.push('test'))
      console.log(this.author.books)
    }

  }
}
</script>
<style></style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值