js数组移动上移下移置顶置底,vue实现表格上下移动置底置顶

js操作数组移动
 
//先封装js数组交换顺序方法
/*参数说明
arr是要操作的数组
index1 是准备移动的元素
index2 是准备移动到的位置 往下移就是 index2=index+1
往上移动就是 index2=index+1;
这个也可以在页面试试那个方法就指导了,但是置顶和置底还有点差别
*/
var swapItems = function(arr, index1, index2,direction) {
if(direction=='up'){//置顶
arr.unshift(arr[index1]);
arr.splice(index1+1,1);
return arr;
}
if(direction=='down'){//置底
arr.push(arr[index1]);
arr.splice(index1,1);
return arr;
}
arr[index1] = arr.splice(index2, 1, arr[index1])[0];
return arr;
};
//然后js调用
function upIndex (index){//置顶
if(index==0){
return;
}
swapItems(myAppList, index,0,'up');
},
function up(index){//上移
if(index == 0) {
return;
}
swapItems(myAppList, index, index - 1);
},
function down(index){//下移
if(index == myAppList.length -1) {
 
return;
}
swapItems(myAppList, index, index + 1);
},
function downIndex(index){//置底
if(index == myAppList.length -1) {
 
return;
}
swapItems(myAppList, index,0,'down');
}
到此 js操作数组移动就完成了 下面用到vue项目里面
 
2. vue操作表格上下移动和置底置顶
项目需求:循环的列表都是dd标签,dd标签右边有四个小按钮从上到下功能依次是:
置顶,上移,下移,置底
html代码
项目的需求用到了大量的vi-if去判断来显示不一样的标签,我刚刚接触vue 感觉我这样写html不是最优的,这里我不知道怎么改进....
另外 4个li标签v-if判断 是因为 如果第一个表格在最上面 就失去一个鼠标移动上去出现上移按钮的效果,这个简单提一下
js代码 记得加上上面封装的js操作数组移动的方法
// vue 循环APP列表页面
var myAppList=[];
//获取myAppList列表
function getMyAppList(){
$.ajax({
url: '你自己的接口地址',
type: 'GET',
dataType: 'json'
})
.done(function(data){
if(data&&data.status){
myAppList=data.result;
var vue= new Vue({
el:'#myAppList',
data:{
myAppList:myAppList
},
methods:{
upIndex:function(index){
if(index==0){
return;
}
swapItems(myAppList, index,0,'up');
},
up:function(index){
if(index == 0) {
return;
}
swapItems(myAppList, index, index - 1);
},
down:function(index){
if(index == myAppList.length -1) {
return;
}
swapItems(myAppList, index, index + 1);
},
downIndex:function(index){
if(index == myAppList.length -1) {
return;
}
swapItems(myAppList, index,0,'down');
}
}
})
}
})
}
//代码算是很简单了 ajax请求返会的json 取一个数组放到vue代码里面,作为vue在html页面 v-for的数据源,剩下的的移动功能就是操作数据源这个大数组的排序了。
vue里面应该有类似的方法,但是我没有找到,所以就用了最笨的办法了。
参考资料:
http://www.111cn.net/wy/js-ajax/80973.htm

转载于:https://www.cnblogs.com/fstgshow/p/5994190.html

你可能感兴趣的:(js数组移动上移下移置顶置底,vue实现表格上下移动置底置顶)