Home > Back-end >  How to store and save data
How to store and save data

Time:05-26

I start to learning store, and i want to upload image, and save it on local. So if i reloaded page image must be saved

store photoUpload.js

const state =  {
  photo: '1'
}
const getters = {
  getPhoto: (state) => {
    return state.photo
  }
}
const mutations = {
  setPhoto(state, photoName) {
    state.photo = photoName
  },
}
const actions = {
  getPhoto(context, photo) {
    context.commit('getPhoto', photo)
  }
}
export const testings = {
  namespaced: true,
  state,
  mutations,
  getters,
  actions,
};

template

<div >
  <img :src="previewImage ? previewImage : 'assets/images/defaultAva.png'"  />
  <label >
    <input ref="imageInput" type="file" name="file" accept="image/png, image/jpeg, image/jpg" @change="uploadImage">
  </label>
</div>

<script>
 data: () => ({
   previewImage: null,
 }),
 computed: {
  getPhoto() {
   return this.$store.getters["photoUpload/getPhoto"];
  },
 },
 methods: {
  uploadImage(e){
   const image = e.target.files[0];
   const reader = new FileReader();
   reader.readAsDataURL(image);
   reader.onload = e =>{
     this.previewImage = e.target.result;
   };
  },
  ...mapActions("testings", ["getPhoto"]),
 },
</script>

So in witch way i must to go, i can upload image to previewImage, but how can i send it to store, to save it locally?

CodePudding user response:

So if i reloaded page image must be saved

The purpose of the store is to save data betweens components locally to all the application but not on page refresh.

From the documentation

A "store" is basically a container that holds your application state

The most common case is to save data from your api into global variables that can be used in all the application using getters as you did.

If you want to keep data on reload you can use other packages like vuex-persist.


In your case if you want to save image to the store you can just use the actions from the mapAction.

Here is how I do it :

methods: {
  uploadImage(e){
   const image = e.target.files[0];
   const reader = new FileReader();
   reader.readAsDataURL(image);
   reader.onload = e =>{
     this.previewImage = e.target.result;
     this.getPhotoToStore(e.target.result) // <-- here 
   };
  },
  ...mapActions({
      getPhotoToStore: "myStore/getPhoto"
  }),
 },

And I use the actions as this :

const actions = {
  getPhoto({ commit }, photo) {
    commit('getPhoto', photo) // <-- commiting to the mutations
  }
}
  • Related