Vue Js Worked Noted - Part 1


This doc useful to remember some new works that has been done in vue js

 INDEX
  • Bool in javascript

  • Downloadable Table Records

  • Redirect / redirect with params 

  • Set state and get state

  • Emit Function

  • JSON. parse()

  • Bind class Based on Condition

-------------------------------------------------------------------------------


Set state and get state


Store - > apicore.js


import { scHelpers } from "~/assets/js/utils";

const { uniqueID } = scHelpers;

export const state = () => ({

  siteIds: []

});

export const getters = {

  getSiteIds(state) {

    return state.siteIds;

  },

};

export const mutations = {

  setSiteIds(state, siteIds) {

    state.siteIds = siteIds;

  },

};

export const actions = {

  fetchSiteIds({ commit, dispatch }) {

    const siteIds = [

      {

        key: uniqueID(),

        value: 1

      },

      {

        key: uniqueID(),

        value: 2

      },

      {

        key: uniqueID(),

        value: 3

      }

    ];

    commit("setSiteIds", siteIds);

  }};


In .vue Pages 


  computed: {

    ...mapGetters({

      siteIdOptions: "apicore/getSiteIds",

    }),






Redirect / redirect with params


  redirectToStateActions(crmState) {

      const redirectPath =

        "/crm_admin/crm_state/" + crmState.stateId + "/crm_state_action";

      this.$nuxt.context.redirect(

        this.$nuxt.context.app.localePath({

          path: redirectPath,

        })

      );

    }






--------------------------------------

  • Bool in javascript


 <select

                          v-show="systemSetting.isSelected"

                          v-model="systemSetting.settingValBool"

                          id="form-h-select"

                          class="uk-select"

                        >

                          <option :value="true">True</option>

                          <option :value="false">False</option>

                        </select>





Downloadable Table Records

https://codepen.io/duc810/pen/MNXOqW


<button

                  id="btnDownload"

                  @click="() => CsvCustomersRegisteredButNotDeposited()"

                  class="sc-button sc-button-primary"

                >

                  Download

                </button>

  button(@click="csvExport(csvData)") Export to CSV 

  

-----------------------------------------


const vm = new Vue({

  el: "#app",

  data: {

    users: [],

  },

  computed: {

    csvData() {

      return this.users.map(item => ({

        ...item,

        address: 'адрес', //item.address.city,

        company: 'компания'//item.company.name

      }));

    }

  },

  methods: {

    csvExport(arrData) {

      let csvContent = "data:text/csv;charset=utf-8,";

      csvContent += [

        Object.keys(arrData[0]).join(";"),

        ...arrData.map(item => Object.values(item).join(";"))

      ]

        .join("\n")

        .replace(/(^\[)|(\]$)/gm, "");


      const data = encodeURI(csvContent);

      const link = document.createElement("a");

      link.setAttribute("href", data);

      link.setAttribute("download", "export.csv");

      link.click();

  

    }

  },

   redirectAgain() {

      const redirectPath =

        "/reports/system_settings/";

      this.$nuxt.context.redirect(

        this.$nuxt.context.app.localePath({

          path: redirectPath,

        })

      );

    },

  async CsvCustomersRegisteredButNotDeposited() {

      try {

        const payload = JSON.parse(JSON.stringify(this.oRequest));

        payload.fromDtTm = this.$moment(payload.fromDtTm, dtTmFormat);

        payload.toDtTm = this.$moment(payload.toDtTm, dtTmFormat);

        payload.pageIndex = this.paginationRequest.currentPage;

        payload.pageSize = 100000;


        const requestUrl =

          "/api/crm/Crm/CsvCustomersRegisteredButNotDeposited";

       

  const response = await this.$axios.post(requestUrl, payload);

        

        var fileURL = window.URL.createObjectURL(new Blob([response.data]));

        var fileLink = document.createElement("a");


        fileLink.href = fileURL;

        fileLink.setAttribute("download", "file.csv");

        document.body.appendChild(fileLink);


        fileLink.click();

      } catch (error) {

        const message =

          "fetchCustomersRegisteredButNotDeposited Error => " + error;

        console.log(message);

      }

    },

});


-----------------------------------



 Emit Function 

Vue components have a $emit() function that allows you to pass custom events up the component tree. Vue. component('my-component', { mounted: function() { // `$emit()` sends an event up the component tree. ... All Vue instances have a $emit() function, including both top-level apps and individual components

https://www.telerik.com/blogs/how-to-emit-data-in-vue-beyond-the-vuejs-documentation


JSON. parse()

  this.items.forEach((element) => {

          if (element.isSelected) {

            const item = JSON.parse(JSON.stringify(element));

 

            item.systemSettingId = parseInt(element.systemSettingId);

            item.settingValInt = parseInt(element.settingValInt);

            item.siteId = parseInt(element.siteId);

 

            payload.items.push(item);

          }

        });



https://www.w3schools.com/js/js_json_parse.asp


The JSON. parse() method parses a JSON string, constructing the JavaScript value or object described by the string


The JSON. stringify() method converts a JavaScript object or value to a JSON string


--------------------------

Bind class

 <div
    v-bind:class="IsAuth"


  computed:{
    ...mapGetters({
      isAuthenticated: 'isAuthenticated',
    }),
    IsAuth: function() {
        if(this.isAuthenticated)
        {
          return '';
        }
        else
        {
          return 'login';
        }    
    }
  }

--------------------------



Comments

Popular posts from this blog

tech note

Vue js Standalone