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返回的


 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM