Vue3:computed()简单使用及使用computed格式化时间

computed

接受一个 getter 函数,返回一个只读的响应式 ref 对象。该 ref 通过 .value 暴露 getter 函数的返回值。它也可以接受一个带有 get 和 set 函数的对象来创建一个可写的 ref 对象

computed(是组合式api,用时引入)

<script setup>
import {ref,computed} from 'vue';


//创建一个只读的计算属性 ref
const count = ref(1)
const plusOne = computed(() => count.value + 1)
console.log(plusOne.value) // 2
plusOne.value++ // 错误


//创建一个可写的计算属性 ref
const count = ref(1)
const plusOne = computed({
  get: () => count.value + 1,
  set: (val) => {
    count.value = val - 1
  }
})
plusOne.value = 1
console.log(count.value) // 0



</script>

延伸:

<script setup>
//引入computed
import {ref,computed} from 'vue';
//使用vuex
let store = useStore();


//时间格式化方法
const formatDate = (event) => {
  let showTime = ""
  let time = new Date(event.replace(/-/g, "/"))
  showTime = (time.getMonth()+1)+'月'+time.getDate()+'日'+time.getHours()+'点'
  return showTime
}


//时间格式化并将23:59:59转为24点00分00秒
const formatTimeDate = (event) => {
  let showsTime = ""
  let times = new Date(event.replace(/-/g, "/"))
  if(times.getHours()== 23 && times.getMinutes()==59 && times.getSeconds()==59){
    showsTime = (times.getMonth()+1)+'月'+times.getDate()+'日'+Number(times.getHours()+1)+'点00分00秒'
  }else{
    showsTime = (times.getMonth()+1)+'月'+times.getDate()+'日'+times.getHours()+'点'
  }
  return showsTime 
}


//使用方法格式化store中存储的数据
const showStarTime = computed(() => {
  return formatDate(store.state.startTime);
})


//判断存在store里面的信息状态
const isLogin = computed(()=> {
  return store.state.userInfo?.token || false
})


//动态展示
const isVip = ref(false)
const userMenu = computed(() => {
  const userArr = ["我的","补充资料"] 
  if(isVip) {
    userArr.push("升级")
  }    
  return userArr
})


</script>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值