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>

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM