简体   繁体   中英

I have problem with sorting my array and I don`t know why

my code have problem and I don t know why it s not working and always give difrent erros I tried anyway the error: 'arraysorted' is not defined no-undef

 <div>
   {{ arraysorted }}
 </div>
</template>

<script>
const Array = [];
export default {
 data: () => ({
   Array: [1, 24, 23, 56, 76, 5, 468, 97, 65, 90, 23, 53, 23],
   arraysorted: [],
 }),
 mounted: {
   ArraySort() {
     return arraysorted = Array.sort(function (a, b) {
       return b - a;
     });
   },
 },
};
</script>  

You can use computed property:

 new Vue({ el: "#demo", data: () => ({ myArray: [1, 24, 23, 56, 76, 5, 468, 97, 65, 90, 23, 53, 23], }), computed: { arraysorted() { const arrSorted = [...this.myArray] return arrSorted.sort((a, b) => b - a) }, }, })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="demo"> {{ arraysorted }} {{myArray}} </div>

mounted() life cycle hook invoked once component mounted. Hence, Instead of writing a method in mounted, You can directly do the sorting and assign the results into arraysorted variable.

Live Demo :

 new Vue({ el: '#app', data: { Array: [1, 24, 23, 56, 76, 5, 468, 97, 65, 90, 23, 53, 23], arraysorted: [] }, mounted() { this.arraysorted = this.Array.sort((a, b) => b - a); } })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <pre>{{ arraysorted }}</pre> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM