简体   繁体   English

Vue.js 洗牌组件

[英]Vue.js shuffle components

I'm making a cup game in Vue.js where there are N number of cups in line and one of them has a dice inside it.我正在 Vue.js 中制作一个杯子游戏,其中有 N 个杯子,其中一个里面有一个骰子。

<cup cupid="a" @onGameStateChange="onGameStateChange" ref="cup" />
<cup cupid="b" @onGameStateChange="onGameStateChange" ref="cup" />
<cup cupid="c" @onGameStateChange="onGameStateChange" ref="cup" />

I would now like to shuffle those cups to move any of the cups around the play field.我现在想对这些杯子进行洗牌,以便在运动场周围移动任何杯子。 Naturally it would mean that I have to move the DOM elements around.自然这意味着我必须移动 DOM 元素。

But I seem to be a bit stuck on how I would achieve this in Vue.js.但我似乎有点坚持如何在 Vue.js 中实现这一点。 I tried attaching a ref (like above) to all of the cups and then getting the DOM element reference for all of the cups but now I'm a bit wondering how would I shuffle those around.我尝试将 ref(如上)附加到所有杯子,然后获取所有杯子的 DOM 元素引用,但现在我有点想知道如何将它们打乱。

I also tried loading the cups from a data array in v-for and then shuffling the cups data property but visually it didn't seem to do anything.我还尝试从v-for中的数据数组加载杯子,然后改组 cups 数据属性,但在视觉上它似乎没有做任何事情。 I also tried it through a compute property.我还通过计算属性进行了尝试。

With Vue.js the fist rule is not to manipulate DOM directly, so how would I achieve this?使用 Vue.js 的首要规则是不直接操作 DOM,那么我该如何实现呢?

Just think in MVVM way.只需以 MVVM 的方式思考。 Your game and three cups are just data, do not mix them up with DOM.你的比赛和三杯只是数据,不要把它们和 DOM 混为一谈。

I write an example blow.我写了一个例子。 Use an array to store cups.使用数组来存储杯子。 Use 'v-for' to generate DOM.使用 'v-for' 生成 DOM。 Shuffle the Cups by "random sort" or "random an array index"!通过“随机排序”或“随机数组索引”来洗牌!

 var demo = new Vue({ el: '#demo', data: { cups: [{name: "cup1"}, {name: "cup2"}, {name: "cup3", imhere: true}] }, methods: { shuffleCups() { this.cups.sort((a, b) => Math.random() > .5 ? -1 : 1); } }, })
 <script src="https://unpkg.com/vue@2.5.16/dist/vue.min.js"></script> <div id="demo"> <button @click="shuffleCups">Shuffle</button> <div v-for="cup in cups"> {{ cup.name }} <span v-if="cup.imhere" style="color: red">*</span> </div> </div>

Update: After written this snippet, I found an example on vuejs.org , it also shows "Transitions & Animation" effect.更新:写完这段代码后,我在 vuejs.org 上找到了一个例子,它也显示了“过渡和动画”效果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM