Vue-js一些練習
1.filter使用 2.Object.keys使用(取得物件屬性) 3.物件內容比對
by cactus77kiki
HTML
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<div id="app">
<h2>Todos:</h2>
<input type="text" v-model="condition"/><br/>
<input type="button" value="find" v-on:click="getbyid()"/>
<input type="button" value="find keys" v-on:click="getobjectkeys()"/>
<input type="button" value="get compare" v-on:click="comparebykey()"/><br/>
<span v-for="(row,index) in result">{{row.id}} - {{row.text}}<br/></span>
<hr/>
<span v-for="(row,index) in keylist">
{{row}}
</span>
<hr/>
<span v-for="(row,index) in comparelist">
{{row.key}} - {{row.value}}<br/>
</span>
</div>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
li {
margin: 8px 0;
}
h2 {
font-weight: bold;
margin-bottom: 15px;
}
del {
color: rgba(0, 0, 0, 0.3);
}
Vue
var app = new Vue({
el: "#app",
data: {
todos: [
{ text: "Learn JavaScript", done: false,kind:"A",id:1 },
{ text: "Learn Vue", done: false,kind:"A",id:2 },
{ text: "Play around in JSFiddle", done: true,kind:"B",id:3 },
{ text: "Build something awesome", done: true,kind:"B",id:4 }
],
condition:"",
result:[],
keylist:[],
comparelist:[]
},
methods: {
//比對物件(note:僅能比對一層,無法比對具多層次的屬性的物件)
comparebykey: function(){
var param = this.keylist;
var ObjA={text: "Learn JavaScript", done: false,kind:"A",id:1};
var ObjB={text: "Learn Math", done: false,kind:"B",id:1};
var result=[];
param.forEach(function(e) {
if ( ObjA[e] != ObjB[e] ){
var eblank={};
eblank.key=e;
eblank.value=ObjB[e];
result.push(eblank);
}
});
this.comparelist = result;
},
//取得物件屬性
getobjectkeys:function(){
var arry = Object.keys(this.result[0]);
this.keylist = arry;
},
//取得資料(byid):filter(回傳陣列)
getbyid: function(){
var param = this.condition;
var findarry = this.todos.filter(function(index){
return index.id>param;
});
this.result = findarry;
},
toggle: function(todo){
todo.done = !todo.done
}
}
})