Ser*_*rgi 4 javascript css vue.js vue-component vuejs2
在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>
Run Code Online (Sandbox Code Playgroud)
这会创建一个内部有4个跨度的div,每个跨度都有一个“ index--0”,“ index--1”等类。
单击时,数组的值更改顺序:
shuffleArray: function() {
const shifted = this.block.shift();
this.block.push( shifted );
}
Run Code Online (Sandbox Code Playgroud)
尽管值确实发生了变化,但它们并未在实际的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;
}
Run Code Online (Sandbox Code Playgroud)
也许有不需要CSS的纯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)
},
}
})Run Code Online (Sandbox Code Playgroud)
.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);
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
42 次 |
| 最近记录: |