假设我有三个div-A,B和c-并且我想在用户单击“重新排序”时更改其顺序。例如,将B放在第一位,将C放在第二位,再将A放在第三位。在Vue中最干净的方法是什么?
编辑:实际上,div中有很多内容,因此使用{ divs: ['A', 'B', 'C'] }
做类似v-for
的事情会太混乱了。
let app = new Vue({
el: '#app',
methods: {
reorder: function () {
},
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div>A</div>
<div>B</div>
<div>c</div>
<button v-on:click="reorder()">Reorder</button>
</div>
答案 0 :(得分:2)
我会说...
在您拥有的数据中:
data: {
return {
blocks: [{
type: 'ComponentA'
content: {
title: 'Foo',
desc: 'lorem ipsum'
}
}, {
type: 'ComponentB'
content: {
title: 'Bar',
desc: 'lorem ipsum'
}
}, {
type: 'ComponentC'
content: {
title: 'Baz',
desc: 'lorem ipsum'
}
}]
}
}
在您拥有的模板中:
<component v-for="(block, i) in blocks" :key="i" :is="block.type"/>
和reorder
对数组进行混洗:How to randomize (shuffle) a JavaScript array?
答案 1 :(得分:0)
这是我想出的:
flex-direction: column
的容器.one { order: 1 }
let app = new Vue({
el: '#app',
data: {
order: {
a: 'one',
b: 'two',
c: 'three',
},
},
methods: {
reorder: function () {
this.order.a = 'three';
this.order.b = 'one';
this.order.c = 'two';
},
},
});
#app {
display: flex;
flex-direction: column;
}
.one { order: 1; }
.two { order: 2; }
.three { order: 3; }
button { order: 4; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-bind:class="order.a">A</div>
<div v-bind:class="order.b">B</div>
<div v-bind:class="order.c">C</div>
<button v-on:click="reorder()">Reorder</button>
</div>
答案 2 :(得分:0)
使用v-for
指令将div绑定到数组数据属性,然后通过您的方法控制数组:
https://jsfiddle.net/efrat19/6y9az8Lv/5/
new Vue({
el: "#app",
data: {
divs: [
'a','d','c']
},
methods: {
reorder: function(){
this.divs.sort();//or any other manipulation on the array
}
}
})
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<div id="app">
<div v-for="div in divs">
{{div}}
</div>
<button @click = "reorder()">reorder</button>
</div>