Skip to content

Instantly share code, notes, and snippets.

@nOy39
Created July 4, 2018 06:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nOy39/661725130b88e3c10b084865b329c100 to your computer and use it in GitHub Desktop.
Save nOy39/661725130b88e3c10b084865b329c100 to your computer and use it in GitHub Desktop.
var bearsApi = Vue.resource('/blog/bears/');
function findIndex(id, bears) {
let i = 0;
bears.forEach(function (element) {
if (element.id === id) {
console.log(i);
return i;
}
i++;
})
return -1;
}
Vue.component('input-form', {
props: ['bears','bearAttr'],
data: function() {
return {
title: '',
body: '',
id:''
}
},
watch: {
bearAttr: function (newVal) {
this.title = newVal.title;
this.body = newVal.body;
this.id = newVal.id
}
},
template:
`<div>
<hr>
<input type="text" placeholder="Blog name" v-model="title"/>
<input type="text" placeholder="Blog body" v-model="body">
<input type="button" value="Save" @click="save"/>
</div> `,
methods: {
save() {
var bear = {
title: this.title,
body: this.body,
id: this.id
};
if (this.id) {
bearsApi.update(bear).then(result =>
result.json().then(data => {
var index = this.id;
this.bears.splice(findIndex(this.id, this.bears),1,data);
this.title = '';
this.body = '';
this.id = '';
}))
} else {
bearsApi.save({}, bear).then(result =>
result.json().then(data => {
this.bears.push(bear);
this.title = '';
this.body = '';
}))
}
}
}
});
Vue.component('bear-list', {
props: ['bears','bearsApi'],
data: function () {
return {
bear: null
}
},
template:
`<div>
<input-form :bears="bears" :bear-attr="bear"/>
<div class="row">
<div class="col-3" v-for="bear in bears" :key="bear.id">
<div class="card" style="width: 18rem">
<div class="card-body">
<h5 class="card-title">{{ bear.title }}</h5>
<p class="card-text">{{ bear.body }}</p>
<span>{{ bear. id }}</span>
<button type="button" class="btn btn-primary" @click="edit(bear)">Изменить</button>
<button type="button" class="btn btn-danger" onclick="delete(bear)">Удалить</button>
</div>
</div>
</div>
</div>
</div>`,
methods: {
edit: function (bear) {
this.bear = bear;
},
delete: function (bear) {
bearsApi.remove(bear).then(result => {
this.bears.splice(this.bears.indexOf(this.bear), 1)
})
}
},
created: function () {
bearsApi.get().then(result =>
result.json().then(data =>
data.forEach(bear => this.bears.push(bear))
)
)
},
}
);
new Vue({
el:"#app",
template: '<bear-list :bears="bears" />',
data: {
bears: [
],
bear: []
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment