javascript - Vue.js,更改数组项的顺序并在 DOM 中进行更改
问题描述
在 Vue 实例中,我有一个名为“block”的数组,其中包含 4 个值。我使用 v-for 将此数组渲染到 DOM:
<div class="block" @click="shuffleArray()">
<div v-for="(number, index) in block">
<span :class="[`index--${index}`]">{{ number }}</span>
</div>
</div>
这将创建一个内部有 4 个跨度的 div,每个跨度都有一个类“index--0”、“index--1”等。
单击时,Array 的值更改顺序:
shuffleArray: function() {
const shifted = this.block.shift();
this.block.push( shifted );
}
虽然值确实发生了变化,但它们并没有在实际的 DOM 中移动,我怎样才能在单击时实现这一点,跨度实际上会在 DOM 中改变位置?每个跨度都应用了一个样式,所以我想要一个值确实改变顺序的视觉表示:
span.index--0 {
background-color: tomato;
}
span.index--1 {
background-color: khaki;
}
span.index--2 {
background-color:lavenderblush;
}
span.index--3 {
background-color: lightcoral;
}
也许有一个不需要 DOM 操作的纯 CSS 解决方案。
解决方案
我建议使用list tranisition
它来制作这样的花哨:
Vue.config.devtools = false;
Vue.config.productionTip = false;
new Vue({
el: '#list-demo',
data: {
items: [1,2,3,4,5,6,7,8,9],
nextNum: 10
},
methods: {
randomIndex: function () {
return Math.floor(Math.random() * this.items.length)
},
add: function () {
this.items.splice(this.randomIndex(), 0, this.nextNum++)
},
remove: function () {
this.items.splice(this.randomIndex(), 1)
},
}
})
.list-item {
display: inline-block;
margin-right: 10px;
}
.list-enter-active, .list-leave-active {
transition: all 1s;
}
.list-enter, .list-leave-to /* .list-leave-active below version 2.1.8 */ {
opacity: 0;
transform: translateY(30px);
}
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="list-demo">
<button v-on:click="add">Add</button>
<button v-on:click="remove">Remove</button>
<transition-group name="list" tag="p">
<span v-for="item in items" v-bind:key="item" class="list-item">
{{ item }}
</span>
</transition-group>
</div>
推荐阅读
- python - 如何将下载和解压缩的文本文件加载到熊猫数据框中?
- python - 使用 sk-learn 基于字符串特征预测数值特征
- javascript - 如何在我的电脑上运行谷歌使用的 JS 代码?
- node.js - 日历邀请 nodejs 中的 icalender
- python - 如何让雪花旋转更顺畅?
- r - 如何使带有前导零的不连续字符数字序列连续?
- delphi - 如何在delphi的TOpenDialog中只过滤纯文本文件
- html - 如何将我的 div 与每个元素的容器右侧对齐?
- javascript - 对象不支持属性或方法匹配 IE11 中的 react-responsive-modal 与 react js
- python - 如何在我的网站上显示我的翻译