随机点名是许多老师用来点名学生的一种有效方式。而如何利用Vue来实现随机点名呢?其实这并不难。
首先,我们需要定义一个students数组,将学生名字存储其中。
data() { return { students: ["小明","小红","小李","小花"] }; }
接下来,我们需要一个按钮来触发随机点名。这个按钮需要绑定一个方法。在这个方法中,我们将随机生成一个数,然后根据这个数从students数组中取出对应的名字,再将这个名字保存到一个selected变量中,最后将这个变量显示在页面上。
methods: { selectStudent() { let num = Math.floor(Math.random() * this.students.length); let selected = this.students[num]; this.selected = selected; } }
在页面中,我们需要一个用来显示选中名字的div,还有一个绑定selectStudent方法的按钮。在这里我们使用了Bootstrap来美化页面。
<div class="container"> <div class="row"> <div class="col-md-12 text-center"> <h1>随机点名器</h1> <p><b>当前选中:{{ selected }}</b></p> <button class="btn btn-primary" v-on:click="selectStudent()">随机点名</button> </div> </div> </div>
最后,我们需要在页面中引用Vue,并将Vue实例绑定到一个div中。
<body> <div id="app"> </div> <!-- 引入Vue.js --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <!-- 创建Vue实例 --> <script> new Vue({ el: '#app',data: {...},methods: {...} }); </script> </body>
通过以上的代码,我们可以实现一个简单的随机点名器。当然你可以根据需求进行更改和扩展,例如添加删除学生、打乱学生顺序等等。