Skip to content

Commit

Permalink
Problem with work saving
Browse files Browse the repository at this point in the history
  • Loading branch information
Dual-Ice committed May 21, 2020
1 parent 918936e commit 37bc2c7
Show file tree
Hide file tree
Showing 5 changed files with 213 additions and 58 deletions.
70 changes: 52 additions & 18 deletions src/admin/components/Works/WorkEdit.vue
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
<template lang="pug">
.work-edit.card
form(@submit.prevent="saveWork")
form(
@submit.prevent="submit"
@reset.prevent="hide")
.form__container
.form__header {{formTitle}}
hr.divider
Expand All @@ -14,7 +16,7 @@
type="button"
@click="showInputFile"
).form__image-btn Изменить превью
.form__load-area(v-else)(:class="photoError")
.form__load-area(v-else :class="photoError")
.form__load-text Перетащите либо загрузите изображение
.form__load-btn
button(
Expand All @@ -27,6 +29,7 @@
)
input(
type="file"
accept=".png, .jpg, .jpeg"
@change="appendFileAndRenderPhoto"
)#upload-pic.form__load-file
.form__col
Expand Down Expand Up @@ -63,20 +66,23 @@
span {{ tag }}
button(
type="button"
@click="delTag(ndx)").tag__remove-btn
@click="delTag(ndx)"
).tag__remove-btn
Icon(
iconName="cross"
className="tag__remove-icon"
)
.form__btns
button(type="reset").form__btn.form__btn--plain Отмена
button(
type="button"
@click="cancelAndHide"
).form__btn.form__btn--plain Отмена
button(type="submit").form__btn.form__btn--big Загрузить
type="submit"
:disabled="isBlocked"
:class="{ 'blocked': isBlocked }"
).form__btn.form__btn--big Загрузить
</template>
<script>
import Icon from "../Icon"
import { mapActions } from 'vuex'
import CustomInput from "../CustomInput"
import InputTooltip from "../InputTooltip"
import { required, minLength, url } from 'vuelidate/lib/validators'
Expand Down Expand Up @@ -105,7 +111,8 @@ export default {
techs: "",
photo: "",
description: ""
}
},
isBlocked: false
}
},
Expand Down Expand Up @@ -149,48 +156,75 @@ export default {
watch: {
'tmpWork.techs'() {
this.tags = this.tmpWork.techs.split(',');
this.tags = this.tmpWork.techs.split(',')
}
},
created () {
Object.assign(this.tmpWork, this.work)
if (this.tmpWork.photo) {
this.tmpWork.photo = `https://webdev-api.loftschool.com/${this.tmpWork.photo}`
}
if (this.tmpWork.techs.length > 0) {
this.tags = this.tmpWork.techs.split(',');
this.tags = this.tmpWork.techs.split(',')
}
},
methods: {
...mapActions('works', ['saveWork', 'updateWork']),
showInputFile () {
document.querySelector("#upload-pic").click()
},
delTag(index) {
this.tags.splice(index, 1);
this.tags.splice(index, 1)
this.tmpWork.techs = this.tags.join(',')
},
appendFileAndRenderPhoto (e) {
const test = e.target.files[0];
const reader = new FileReader();
const test = e.target.files[0]
const reader = new FileReader()
try {
reader.readAsDataURL(test);
reader.readAsDataURL(test)
reader.onload = () => {
this.tmpWork.photo = reader.result;
};
this.tmpWork.photo = reader.result
}
} catch (error) {
console.log(error)
}
},
saveWork () {
async submit () {
this.$v.$touch()
if (!this.$v.$error) {
try {
this.isBlocked = true
const isWorkChanged = Object.keys(this.tmpWork).some((key, value) => this.work[key] !== value);
if (isWorkChanged) {
this.tmpWork.id
? await this.updateWork(this.tmpWork)
: await this.saveWork(this.tmpWork)
}
this.hide()
} catch (error) {
console.log(error)
} finally {
this.isBlocked = false
}
console.log("All is ok: ", this.tmpWork)
}
},
cancelAndHide () {
hide () {
this.$emit('hide')
},
validationMessage (field) {
Expand Down
115 changes: 76 additions & 39 deletions src/admin/components/Works/Works.vue
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@
h1.page-title.works__title Блок «Работы»
.works__content
.container.works__container
WorkEdit(v-if="showAddWork")
WorkEdit(
v-if="showAddWork"
:work="work"
@hide="hideAddWork")

ul.works__list
li.works__item
Expand All @@ -18,12 +21,14 @@
:key="work.id"
)
work(
:value="work")
:value="work"
@edit="editWork")
</template>
<script>
import Work from "./Work"
import AddBtn from "../AddBtn"
import WorkEdit from "./WorkEdit"
import Work from './Work'
import AddBtn from '../AddBtn'
import WorkEdit from './WorkEdit'
import { mapState, mapActions } from 'vuex'
export default {
components: {
Work,
Expand All @@ -32,49 +37,81 @@ export default {
},
created() {
this.works = this.makeArrWithRequireImages(this.works)
this.loadWorks(this.user.id)
// this.works = this.makeArrWithRequireImages(this.works)
},
data () {
return {
works: [
{
"id": 1,
"title": "Сайт об экстримальном отдыхе",
"skills": "Html, Css, JavaScript",
"image": "1.jpg",
"link": "//google.com",
"desc": "Этот парень проходил обучение веб-разработке не где-то, а в LoftSchool! 2 месяца только самых тяжелых испытаний и бессонных ночей!"
},
{
"id": 2,
"title": "Сайт небольшого города",
"skills": "Pug, PostCss, VueJS",
"image": "2.jpg",
"link": "//yandex.ru",
"desc": "Повседневная практика показывает, что постоянный количественный рост и сфера нашей активности требует от нас анализа форм воздействия. "
},
{
"id": 3,
"title": "Сайт автомобильного журнала",
"skills": "Laravel, Saas, React",
"image": "3.jpg",
"link": "//rambler.ru",
"desc": "Дорогие друзья, повышение уровня гражданского сознания играет важную роль в формировании существующих финансовых и административных условий."
}
],
showAddWork: false
showAddWork: false,
work: {
title: '',
link: '',
description: '',
techs: '',
photo: null
}
// works: [
// {
// "id": 1,
// "title": "Сайт об экстримальном отдыхе",
// "skills": "Html, Css, JavaScript",
// "image": "1.jpg",
// "link": "//google.com",
// "desc": "Этот парень проходил обучение веб-разработке не где-то, а в LoftSchool! 2 месяца только самых тяжелых испытаний и бессонных ночей!"
// },
// {
// "id": 2,
// "title": "Сайт небольшого города",
// "skills": "Pug, PostCss, VueJS",
// "image": "2.jpg",
// "link": "//yandex.ru",
// "desc": "Повседневная практика показывает, что постоянный количественный рост и сфера нашей активности требует от нас анализа форм воздействия. "
// },
// {
// "id": 3,
// "title": "Сайт автомобильного журнала",
// "skills": "Laravel, Saas, React",
// "image": "3.jpg",
// "link": "//rambler.ru",
// "desc": "Дорогие друзья, повышение уровня гражданского сознания играет важную роль в формировании существующих финансовых и административных условий."
// }
// ],
}
},
computed: {
...mapState('works', ['works']),
...mapState('auth', ['user'])
},
methods: {
makeArrWithRequireImages(array) {
return array.map((item) => {
const requirePic = require(`../../../images/content/works/${item.image}`);
item.image = requirePic;
return item;
});
...mapActions('works', ['loadWorks']),
hideAddWork() {
this.showAddWork = false
Object.assign(
this.work,
{
title: '',
link: '',
description: '',
techs: '',
photo: null
}
)
},
editWork(){
}
// makeArrWithRequireImages(array) {
// return array.map((item) => {
// const requirePic = require(`../../../images/content/works/${item.image}`);
// item.image = requirePic;
// return item;
// });
// }
}
}
Expand Down
8 changes: 7 additions & 1 deletion src/admin/store/index.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
import Vue from 'vue'
import Vuex from 'vuex'
import auth from './modules/auth'
import works from './modules/works'
import reviews from './modules/reviews'
import categories from './modules/categories'
Vue.use(Vuex);

export default new Vuex.Store({
modules: {
auth
auth,
works,
reviews,
categories
}
});
69 changes: 69 additions & 0 deletions src/admin/store/modules/works.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import axios from '../../customAxios'
import formData from '../../utils/formData';

export default {
namespaced: true,

state: {
works: []
},

mutations: {
setWorks (state, works) {
state.works = works
},

addWork (state, work) {
state.works = [...works, work]
},

setWork (state, work) {
state.works = state.works.map(item => item.id === work.id ? work : item)
},

removeWork (state, workId) {
state.works = state.works.filter(work => work.id !== workId)
}
},

actions: {
async loadWorks ({ commit }, userId) {
try {
const { data } = await axios.get(`/works/${userId}`)
commit('setWorks', data)
} catch (error) {
console.log(error)
}
},

async saveWork ({ commit }, work) {
try {
const { data } = await axios.post(
'/works',
formData(work),
{ headers: { 'Content-Type': 'multipart/form-data' }
})

commit('addWork', data)
} catch (error) {
throw new Error(error)
}
},
async updateWork ({ commit }, payload) {
try {
const { data } = await axios.post(`/works/${payload.id}`, formData(payload), { headers: { 'Content-Type': 'multipart/form-data' } })
commit('setWork', data)
} catch (error) {
console.log(error)
}
},
async deleteWork ({ commit }, workId) {
try {
await axios.delete(`/works/${workId}`)
commit('removeWork', workId)
} catch (error) {
console.log(error)
}
}
}
}
9 changes: 9 additions & 0 deletions src/admin/utils/formData.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export default (payload) => {
const formData = new FormData()

Object.keys(payload).forEach(key => {
formData.append(key, payload[key])
})

return formData;
}

0 comments on commit 37bc2c7

Please sign in to comment.