基于Vue的简易大冒险选择器组件化改进
界面如下图所示:
界面以两个界面为主,可以新加界面,组件化后添加简单,只需要添加不同的数组就可以实现复用。组件化消除了复用相差不大的程序,而添加一倍工作量代码的麻烦。由于刚接触前端自学不久,写博客也只是让自己思路理顺一遍,巩固一下知识,所以有什么问题希望看到的大佬帮忙指正,万分感谢。
完整代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>time</title>
<style>
input{
display: block;
height: 80px;
width: 500px;
line-height: 80px;
color: red;
margin: 0 auto;
text-align: center;
font-size: 70px;
}
span {
display: block;
margin: 20px auto;
text-align: center;
}
</style>
</head>
<body>
<div id="app">
<xh-setimer v-model="arr"></xh-setimer>
<xh-setimer v-model="arr1"></xh-setimer>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
Vue.component("xh-setimer",{
props: {
value:{
type:Array,
required:true
}
},
template: `
<div>
<input type="text" v-model="text" >
<span>
<button @click="begin()">开始</button>
<button @click="stop()">确认</button>
</span>
</div>
`,
data: function () {
return{
stopstate:false,
text:"",
childarr:this.value
}
},
methods: {
begin: function () {
this.stopstate = false;
var i = 0;
var that = this;
var timer = setInterval(time, 100)
function time() {
that.text = that.childarr[i].label;
i++;
if (i == that.childarr.length) {
i = 0;
}
if (that.stopstate == true) {
clearInterval(timer)
}
}
},
stop: function () {
this.stopstate = true;
},
}
})
var app = new Vue({
el:"#app",
data:{
arr:[
{id:0,label:"aa"}, {id:1,label:"bb"}, {id:2,label:"cc"},
{id:3,label:"dd"}, {id:4,label:"ee"}, {id:5,label:"ff"},
{id:6,label:"gg"}, {id:7,label:"hh"}, {id:8,label:"ii"},
],
arr1:[
{id:0,label:"a"}, {id:1,label:"b"}, {id:2,label:"c"},
{id:3,label:"d"}, {id:4,label:"e"}, {id:5,label:"f"},
{id:6,label:"g"}, {id:7,label:"h"}, {id:8,label:"i"},
],
},
})
</script>
</body>
</html>
核心还是在于setInterval函数,昨天刚记录了一下这个,所以不做过多解释。这段代码比昨天记录的代码的优点在于进行了组件封装,可以在大大简化代码量的前提下进行复用。
有什么问题希望看到的大佬帮忙指正,也不知道组件封装的对不对,只是功能可以正常实现,所以写出来希望看到这篇博文的批评指正一下。