vue 的函数和属性的计算的写法computed

计算有多少条数据,并显示数据的个数(有两种方法,一种是函数的写法,一种是属性的计算使用computed)
<template>
  函数的写法 :{{getResourceListLength()}}
  计算属性的写法:{{getResourceListLength}}
</template>
 
<script>
import {toRefs, reactive,computed} from "vue";
import ResourceList from '@/components/ResourceList.vue';
 
export default {
    components:{
        ResourceList,
    },setup(){
        const data=reactive({
            resource:[
                {
                    _id:"1",
                    title:"新闻1",
                    description:"新闻新闻",
                    type:"video",
                    link:""
                },
                {
                    _id:"2",
                    title:"新闻2",
                    description:"新闻新闻",
                    type:"video2",
                    link:""
                },
                {
                    _id:"3",
                    title:"新闻3",
                    description:"新闻新闻",
                    type:"video3",
                    link:""
                },
                {
                    _id:"4",
                    title:"新闻4",
                    description:"新闻新闻4",
                    type:"video",
                    link:""
                },
                {
                    _id:"5",
                    title:"新闻5",
                    description:"新闻新闻5",
                    type:"video",
                    link:""
                },
                {
                    _id:"6",
                    title:"新闻6",
                    description:"新闻新闻6",
                    type:"video",
                    link:""
                },
                {
                    _id:"7",
                    title:"新闻7",
                    description:"新闻新闻7",
                    type:"video",
                    link:""
                }
            ]
        })
       
        // 获取数据的个数(写法一)
        // const getResourseListLength = () =>{
        //     return data.resource.length;
        // };
        //获取数据个数(写法二)
         const getResourseListLength =  computed(() =>{
            return data.resource.length;
        });
        return{...toRefs(data),getResourseListLength}//数据解包
    }
}
 

注意:如果使用函数计算的时候,不需要使用computed的函数,当时用属性计算的时候,是需要computed函数来计算的,同时需要在顶部进行computed的引入,虽然写法差不多,但是如果针对于一个时常变动的数字的时候使用computed的方式来计算,性能会更高,同时,注意在顶部template中的写法,函数需要在函数名之后加上(),而计算属性不需要,只需要写函数名即可。不论是函数还是计算属性都是需要进行return返回的


 

posted @ 2020-11-14 20:16  一封未寄出的信  阅读(1173)  评论(0编辑  收藏  举报