本人刚接触vue.js,技术不够,望各位大神留情
------------------------------------------------------------------------------------------------------------
首先感谢作者 @尤小右 大大边写的超级带感的 Vue.js 前端框架,赠送的几个小例子都很有代表性,代码逻辑清晰简明,不禁想自己改装一下
先定义一个组数据,存放在json文件中
{ "master":{"0":{"id":"0","username":"sky0","psd":"123456"}, "1":{"id":"1","username":"sky1","psd":"abcdef"}, "2":{"id":"2","username":"sky2","psd":"qweqw"}, "3":{"id":"3","username":"sky3","psd":"ewerw"} }, "dev":{"0":{"id":"0","username":"snow0","psd":"123456"}, "1":{"id":"1","username":"snow1","psd":"abcdef"}, "2":{"id":"2","username":"snow2","psd":"qweqw"}, "3":{"id":"3","username":"snow3","psd":"ewerw"} } }
html文件如下:
<div id="demo"> <template v-for="branch in branches"> //通过v-for循环创建按钮,并为每个按钮添加点击事件(fetchDat(branch))并传值
<input type="button" :id="branch" :value="branch" name="branch" ref="branch" v-on:click="fetchData(branch)" >
</template>
<ul>
<li style='display:flex' v-for="commit in commits"> //遍历commits将commits中的数据绑定到下面的span标签中
<span style="flex:1">{{ commit.id }}</span>
<span style="flex:1">{{ commit.username }}</span>
<span style="flex:1">{{ commit.psd }}</span>
</li>
</ul>
</div>
定义一个Vue模块
var apiURL = 'data/test1.json', //定义一个数据路径 var vm = new Vue({ el: '#demo', //定义vue挂载的元素节点 data: { branches: [], currentBranch: '', commits: '' }, created: function() { //生命周期的钩子,在实例创建后同步调用(一般在此处调用ajax获取页面初始化所需要的数值) this.load(); this.title(); }, watch: { //对象,键是观察表达式,值可以是方法名,也可以是对象,在实例化是为每个键调用$watch
currentBranch: 'load'
},
methods: {
fetchData: function(branch) { //点击上面的调用的函数接受上面传递的参数
var xhr = new XMLHttpRequest(); //实例化XMLHttpRequest
currentBranch=branch; //将接受的参数赋给currentBranch
var self = this; //this自动绑定为Vue实例(不应该使用箭头函数来定义methods函数,否则this将不会按照期望指向Vue实例)
xhr.open('GET', apiURL);
xhr.onload = function() {
self.commits = (JSON.parse(xhr.responseText))[currentBranch]; //获取到上面的json文件并且取到此时被点击的按钮所对应的数据
}
xhr.send();
},
title:function(){ //初始化branches所对应的数据
var xhr = new XMLHttpRequest();
var self = this;
xhr.open('GET', apiURL);
xhr.onload = function () {
self.box = (JSON.parse(xhr.responseText));
var branches_arr=[]; //定义一个数组用来存放获取到的数据中的标题
for(var i in self.box){
branches_arr.push(i);
}
self.branches=branches_arr; //将branches_arr中的值赋branches
self.currentBranch=branches_arr[0];//将branches_arr中的第一个值赋currentBranch用来初始化界面(即在按钮未被点击时为界面定义默认数据)
}
xhr.send();
}
}
});