简体   繁体   English

我对数组排序有问题,我不知道为什么

[英]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我的代码有问题,我不t know why it不起作用并且总是给出不同的错误我还是尝试了错误:'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.组件安装后调用mounted()生命周期钩子。 Hence, Instead of writing a method in mounted, You can directly do the sorting and assign the results into arraysorted variable.因此,您可以直接进行排序并将结果分配给arraysorted变量,而不是在mounted中编写方法。

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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