vue3-setter/getter和计算属性

<template>
  <div id="app">
    <p>姓名:{{name}}</p>
    <p>
      <button @click="changeAge(-1)">-</button>
      年龄:{{age}}
      <button @click="changeAge(1)">+</button>
    </p>
    <p>出生年份:<button @click="changeYear(-1)">-</button>
      {{year}}
      <button @click="changeYear(1)">+</button>
    </p>
  </div>
</template>

<script>
import {ref,computed} from 'vue'
export default {
  name:'app',
  data(){
    return {
      name:'xiaosan'
    }
  },
  setup(){
    const name =ref('小四')
    const age=ref(18)
    const year=computed({
      get:()=>{
        return 2020-age.value
      },
      set: val=>{
        age.value=2020-val;
      }
    });
    // const year=computed(()=>{
    //   return 2020-age.value
    // })
    function changeAge(val){
      age.value +=val //想改变值或获取值 必须.value
    }
    function changeYear(val){
      year.value=year.value+val
    }
    return { //必须返回 模板中才能使用
      name,age,changeAge,year,changeYear
    }
  }
}
</script>

 

posted on 2020-09-01 11:06  秃了头也不退休  阅读(1406)  评论(0编辑  收藏  举报

导航