假设一个div中有多个子组件,多个子组件可以上下移动:
如上图所示; 在子组件上点击上下,可以交换顺序。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id='app'>
<app></app>
<div>
<div ref='com1'><com1></com1></div>
<div ref='com2'><com2></com2></div>
<div ref='com3'><com3></com3></div>
</div>
</div>
<script>
var vm = new Vue({
el:'#app',
data:{
title:'预处理'
},
methods:{
changeSequence(upOrDown,componentName){
if (upOrDown == 1) {
var preComponent = this.$refs[componentName].previousElementSibling
console.log(preComponent)
if (!preComponent) {
return;
}
this.$refs[componentName].after(preComponent)
}
if (upOrDown == -1) {
var nextComponent = this.$refs[componentName].nextElementSibling
console.log(nextComponent)
if (!nextComponent) {
return;
}
this.$refs[componentName].before(nextComponent)
}
}
},
components:{
com1:{
name:'com1',
data(){
return {
'title':'子组件1'
}
},
template:'<div><h1> </h1> <a href="#" @click=moveUp>上</a> <span></span> <a href="#" @click=moveDown>下</a></div> ',
methods:{
moveUp(){
this.$parent.changeSequence(1, this.$options.name)
},
moveDown(){
this.$parent.changeSequence(-1,this.$options.name)
},
}
},
com2:{
name:'com2',
data(){
return {
'title':'子组件2'
}
},
template:'<div><h1> </h1> <a href="#" @click=moveUp>上</a> <span></span> <a href="#" @click=moveDown>下</a></div> ',
methods:{
moveUp(){
this.$parent.changeSequence(1, this.$options.name)
},
moveDown(){
this.$parent.changeSequence(-1,this.$options.name)
},
}
},
com3:{
name:'com3',
data(){
return {
'title':'子组件3'
}
},
template:'<div><h1> </h1> <a href="#" @click=moveUp>上</a> <span></span> <a href="#" @click=moveDown>下</a></div> ',
methods:{
moveUp(){
this.$parent.changeSequence(1, this.$options.name)
},
moveDown(){
this.$parent.changeSequence(-1,this.$options.name)
},
}
}
}
})
</script>
</body>
</html>
this.$parent
&& this.$refs
在子组件中通过this.$parent
可以调用父类方法,当需要使用dom元素时,插入ref属性:
在将子组件上下移动时,实际上就是各个div的元素进行after
、before
操作; 不能用appen
—在父元素末尾添加元素。
dom操作after
、before
时,不需要自己手动控制display:none
你看那个人好像一条狗啊