写vue demo(模拟给一个列表数据根据某个属性排序)时,升序降序没问题,还原原来顺序就回不去了。
- <script setup lang='ts'>
- import {unref, ref, watch} from "vue";
- const list = [{name:'刘亦菲',age: 26},{name:'周星驰',age: 55},{name:'安悦溪',age: '25'},{name:'杨幂',age: 18},{name:'胡歌',age: 40}];
-
- const showList = ref(list);
- const type = ref(0);
-
- watch(() => unref(type),(value) => {
- console.log(value)
- if(value === 1){
- showList.value.sort((a:any,b:any) => b.age - a.age);
- }else if(value === 2){
- showList.value.sort((a:any,b:any) => a.age - b.age);
- }else {
- showList.value = list;
- }
- })
- script>
-
- <template>
- <div>
- <div class="table-header">
- <span>namespan>
- <span>agespan>
- <span>升序span>
- <span>降序span>
- <span>原顺序span>
- div>
- <div class="table-item" v-for="{name,age} in showList">
- <span>{{name}}span>
- <span>{{age}}span>
- div>
- div>
- template>
然后想着可能是直接赋值引起的,我再浏览器控制台测试了一下,发现果真是这样:
最后解决办法是:
- const showList = ref([...list]);//or
- const showList = ref(list.slice(0));
这是因为:进行对象赋值的时候,赋值的是对象的引用,改变复制后的数组会影响到原来的变量的值.