Categories
VueJS

Common useful Vue 3 APIs and Macros

In this article we are going to list some common and useful Vue Apis and Macros that can help you in day to day coding.

computed

const count = ref(1)
const plusOne = computed(() => count.value + 1)
console.log(plusOne.value) // 2
plusOne.value++ // error

//As a getter/setter
const count = ref(1)
const plusOne = computed({
  get: () => count.value + 1,
  set: val => {
    count.value = val - 1
  }
})

plusOne.value = 1
console.log(count.value) // 0

watchEffect

const count = ref(0)

watchEffect(() => console.log(count.value))
// -> logs 0

setTimeout(() => {
  count.value++
  // -> logs 1
}, 100)

watch
The watch API is the exact equivalent of the Options API this.$watch (and the corresponding watch option). watch requires watching a specific data source and applies side effects in a separate callback function. It also is lazy by default – i.e. the callback is only called when the watched source has changed.
A watcher data source can either be a getter function that returns a value, or directly a ref:

// watching a getter
const state = reactive({ count: 0 })
watch(
  () => state.count,
  (count, prevCount) => {
    /* ... */
  }
)

// directly watching a ref
const count = ref(0)
watch(count, (count, prevCount) => {
  /* ... */
})

$emit
Trigger an event on the current instance. Any additional arguments will be passed into the listener’s callback function.

<div id="emit-example-argument">
  <advice-component v-on:advise="showAdvice"></advice-component>
</div>

const app = createApp({
  methods: {
    showAdvice(advice) {
      alert(advice)
    }
  }
})

app.component('advice-component', {
  emits: ['advise'],
  data() {
    return {
      adviceText: 'Some advice'
    }
  },
  template: `
    <div>
      <input type="text" v-model="adviceText">
      <button v-on:click="$emit('advise', adviceText)">
        Click me for sending advice
      </button>
    </div>
  `
})

app.mount('#emit-example-argument')
Categories
Quasar VueJS

How to create a Custom Select Component in Quasar V2 using <script setup> SFC

In this post we are going to wrap Quasar V2 q-select in a custom base component we can reuse. The q-select has many props and options and sometime we want some of these props to be available by default for all our select components. Same goes for the styling, sometimes we require our q-select’s to have the same look and feel or wrapped in some custom HTML that has a common look and feel across our website or App.

For such cases a custom Select Component is quite handy. In a similar manner we can wrap other components like q-input, q-uploader etc as well if required.

Below is the sample code for creating a custom Select Component wrapping the quasar’s q-select. Please note we have used Vue 3′ script setup SFC API in this and it will not work if you are using Vue 2 or Quasar V1.

<template>
  <div>
    <q-select
      :options="arrMatchedOptions"
      use-input
      outlined
      dense
      hide-selected
      hide-bottom-space
      fill-input
      map-options
      input-debounce="0"
      :option-value="strOptionValue"
      :option-label="strOptionLabel"
      option-disable="inactive"
      :label="strLabel"
      emit-value
      clearable
      :modelValue="modelValue"
      @update:model-value="fnEmit"
      :loading="blnLoading"
      :rules="arrRules"
      :disable="blnDisabled"
      @filter="fnFilter"
    ></q-select>
  </div>
</template>

<script setup>
import { computed, onMounted, ref } from "vue"
import { myUtils } from '@/boot/utils'

const props = defineProps({
  modelValue: { required: true },
  strLabel: {
    type: String,
    required: true
  },
  strOptionLabel: {
    type: String,
    required: false,
    default: 'name'
  },
  strOptionValue: {
    type: String,
    required: false,
    default: 'id'
  },
  arrOptions: {
    type: Array,
    required: true
  },
  blnLoading: {
    type: Boolean,
    default: false
  },
  blnRequired: {
    type: Boolean,
    default: false
  },
  blnDisabled: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue'])


const arrMatchedOptions = ref(JSON.parse(JSON.stringify(props.arrOptions)));

const arrRules = computed(() => {
  if (props.blnRequired) {
    return [myUtils.requiredSelectRule]
  }
  return []
}
);

onMounted(() => {
});


const fnFilter = (strVal, update) => {

  if (strVal === '') {
    update(() => {
      arrMatchedOptions.value = props.arrOptions
    })
    return
  }

  update(() => {
    const strNeedle = strVal.toLowerCase()
    arrMatchedOptions.value = props.arrOptions.filter(obj => {
      const strOptionLabel = obj[props.strOptionLabel]
      return strOptionLabel.toLowerCase().indexOf(strNeedle) > -1
    })
  })
};

const fnEmit = ($event) => {

  emit('update:modelValue', $event)
}

How to use in your parent component, below is an example code:

<template>
  <q-layout>
    <q-card>
      <q-card-section class="p20px">
        <div class="sectionTitle">
          <h2>Base Select Test</h2>
          <span class="after"></span>
        </div>

        <div class="mt20px row">
          <BaseSelect
            :arrOptions="arrGender"
            strLabel="Gender"
            strOptionLabel="name"
            strOptionValue="id"
            v-model="gender"
            hide-bottom-space
          ></BaseSelect>
        </div>
      </q-card-section>
    </q-card>
  </q-layout>
</template>

<script setup>
import { ref } from "vue"
import BaseSelect from "./components/BaseSelect.vue"

const arrGender = ref([
  { name: 'Male', id: 'm' },
  { name: 'Female', id: 'f' },
  { name: 'Other', id: 'o' },
]);

const gender = ref('')
Categories
VueJS

The New Vue by Evan You – VueConf Toronto 2021

Latest on VueJS by Evan You in VueConf Toronto 2021.

Link to Slides: https://docs.google.com/presentation/d/1NntydB8nwtTpcIuKg6O1s_ZeGJKtffTn39Wi1OHhts0/edit#slide=id.p

Categories
PHP

How to detect a user agent or device in PHP

In this tutorial we will see how you can check for a device or user agent using a third party script known as Mobile_Detect.php.

It is a lightweight PHP Class and can be integrated by downloading and requiring in your php script or can be installed via Composer.

For a quick integration, you can simply download the class from here:

https://github.com/serbanghita/Mobile-Detect/blob/master/Mobile_Detect.php

Below is a sample php script for testing whether the device or user agent is a Tablet, Desktop, Mobile etc.

<?php 
// Include and instantiate the class.
require_once 'Mobile_Detect.php';
$detect = new Mobile_Detect;
 
// Any mobile device (phones or tablets).
if ( $detect->isMobile() ) {
  echo "I am a mobile phone";
}
 
// Any tablet device.
if( $detect->isTablet() ){
  echo "I am a tablet";
}
 
// Exclude tablets.
if($detect->isMobile() && !$detect->isTablet() ){
  echo "I am  a mobile not a tablet";
}
 
if(!$detect->isMobile() && !$detect->isTablet() ){
  echo "I am neither a mobile nor a tablet";
}

// Check for a specific platform with the help of the magic methods:
if( $detect->isiOS() ){
  echo "I am on iOS"; 
}
 
if( $detect->isAndroidOS() ){
  echo "I am on Android"; 
}
 
 
// Batch mode using setUserAgent():
$userAgents = array(
'Mozilla/5.0 (Linux; Android 4.0.4; Desire HD Build/IMM76D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19',
'BlackBerry7100i/4.1.0 Profile/MIDP-2.0 Configuration/CLDC-1.1 VendorID/103',
// [...]
);
foreach($userAgents as $userAgent){
 
  $detect->setUserAgent($userAgent);
  $isMobile = $detect->isMobile();
  $isTablet = $detect->isTablet();
  // Use the force however you want.
 
}
 
// Get the version() of components.
// WARNING: this method is in BETA, some keyword properties will change in the future.
if($detect->version('iPad'))
  echo "I am iPad: "; // 4.3 (float)

if($detect->version('iPhone'))
  echo "I am iPhone: " ; // 3.1 (float)

if($detect->version('Android'))
  echo "I am Android: " ; // 2.1 (float)

if($detect->version('Opera Mini'))
  echo "I am Opera Mini: "; // 5.0 (float)

Categories
PHP Qcubed/Qcodo

How to use jQuery Datatables with Qcubed/Qcodo using Ajax Actions

In this tutorial we are going to look in to a quick way to use jQuery data tables with Ajax Actions. This can save you a lot of time if you are wanting to display custom reports or data in a tabular form that can be easily sorted, searched and paginated as well.

We will not use Qcubed/Qcodo datagrids for this example, Below are the sample php form and template file you will require. The code is pretty simple and self explanatory.

Below is the demo.php file

<?php
require ("framework/qcubed.inc.php"); 

	class DemoForm extends QForm {
		  
		protected $lstProduct;
		protected $calStartDate;
		protected $calEndDate;
		protected $btnSearch;
		protected $lblReport;
 
	    protected function Form_Run() { 
	    }
	    
	    protected function Form_Create() {
	        parent::Form_Create();
	         
			$this->lstProduct = new QListBox($this);
			$this->lstProduct->Name = "Product";
			$this->lstProduct->AddItem('-All Products-', null);
 			$arrAndCon = array();
 			$arrAndCon[] = QQ::Equal(QQN::Product()->Enabled, 1);
			$arrProduct = Product::QueryArray(QQ::AndCondition($arrAndCon), QQ::Clause(QQ::OrderBy(QQN::Product()->Name, true)));
			foreach($arrProduct as $objProduct){
				$this->lstProduct->AddItem($objProduct->Name, $objProduct->Id); 
			} 
			
			$this->calStartDate = new QCalendar($this);
 			$this->calStartDate->ShowButtonPanel = true;
			$this->calStartDate->Name = "Start Date"; 
 
			$this->calEndDate = new QCalendar($this);
 			$this->calEndDate->ShowButtonPanel = true;
			$this->calEndDate->Name = "End Date";
    
			$this->btnSearch = new QButton ( $this );
			$this->btnSearch->Text = QApplication::Translate ( 'Search' );
			$this->btnSearch->AddAction ( new QClickEvent (), new QAjaxAction ( 'btnSearch_Click' ) );
 			
			$this->lblReport = new QLabel($this);   
			$this->lblReport->HtmlEntities = false;
  	    } 

 

		protected function btnSearch_Click(){
		 
			if(!$this->calStartDate->DateTime) { $this->calStartDate->Warning = ("Start Date is required."); return false; }
			if(!$this->calEndDate->DateTime) { $this->calEndDate->Warning =  ("End Date is required."); return false; }
		

			$strHtml = <<<TTT
<table id="tblProduct" class="display" style="width:100%">
<thead>
<tr>
<th>Product</th> 
<th>Amount</th> 
</tr>
</thead>
<tbody>
TTT;
 

$arrProduct = array('TEST Product 1' => 12, "TEST Product 2" => 3);
foreach($arrProduct as $strName => $fltValue){  
 
$strHtml .=  "<tr>
<td>$strName</td> 
<td>".$fltValue."</td> 
</tr>";

}

$strHtml .= <<<TTT
</tbody>
<tfoot>
	<tr>
	<th>Product</th> 
	<th>Amount</th> 
	</tr>
</tfoot>
</table>
TTT;
 

$this->lblReport->Text = $strHtml;  

$strJS = "jQuery('#tblProduct').DataTable({'order': [[1, 'desc']]});";
QApplication::ExecuteJavascript($strJS);

		  
		}

    }
		     
	DemoForm::Run('DemoForm');
?>

and the demo.tpl.php

<?php $this->RenderBegin(); ?>


<section class="content">
    <div class="row">
        <div class="col-xs-12"><strong>Product:</strong><?php $this->lstProduct->RenderWithError(); ?></div>
    </div>

    <div class="row">
        <div class="col-xs-6"><strong>From Date:</strong><?php $this->calStartDate->RenderWithError(); ?></div>
        <div class="col-xs-6"><strong>To Date:</strong><?php $this->calEndDate->RenderWithError(); ?></div>
    </div>

    <div class="row">
        <div class="col-xs-12"> <?php $this->btnSearch->Render('CssClass=btn btn-primary'); ?></div>
    </div>
 
    <?php
    $this->lblReport->Render();
    ?>  
</section>
<?php $this->RenderEnd(); ?>
 

Please note in the tpl.php, in addition to the above code, the following Javascript library files and css files are required:

  • https://code.jquery.com/jquery-3.5.1.js
  • https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js
  • https://cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css
Categories
Javascript

Javascript common array methods

In this tutorial we are going to review the most common and used methods to manipulate arrays in Javascript. A cheat
sheet of array methods are listed below:

To add/remove elements:
  • push(...items) – add an item to the end of array.
    Example:
    const arr = ["Black", "Green", "Yellow", "Red"];
    arr.push("Orange"); // Adds "Orange"
  • pop() – extracts an item from the end of array.
    Example:
    const arr = ["Black", "Green", "Yellow", "Red"];
    const str = arr.pop(); // Removed "Red" from arr and assign
    it to str
  • shift() – extracts an item from the beginning of array.
    Example:
    const arr = ["Black", "Green", "Yellow", "Red"];
    const str = arr.shift(); // Removed "Black" from arr and
    assign it to str
  • unshift() – adds items to the beginning of array and returns the new length.
    Example:
    const arr = ["Black", "Green", "Yellow", "Red"];
    const str = arr.unshift("Orange", "Violet"); // Adds
    ["Orange", "Violet"] to the beginning or arr which will now be ["Orange", "Violet", "Black", "Green", "Yellow",
    "Red"] and assign new length i.e 6 to str
  • splice(pos, deleteCount, ...items) – at
    index pos deletes deleteCount elements and inserts items
    Example:
    const arr = ["Black", "Green", "Yellow", "Red"]; arr.splice(2, 0, ["Orange", "Violet"]); // Adds ["Orange",
    "Violet"] after "Green", new arr will now be [ "Black", "Green", "Orange", "Violet", "Yellow", "Red"]
  • slice(start, end) – creates a new array, copies elements from
    index start till end (not inclusive) into it.
    Example:
    const arr = ["Black", "Green", "Yellow", "Red"];
    const arrNew = arr.slice(1, 3); //Assign ["Green", "Yellow"]
    to arrNew, arr remains unaffected
  • concat(...items) – returns a new array: copies all members of the current one and
    adds items to it. If any of items is an array, then its elements are taken.
    Example:
    const arr = ["Black", "Green", "Yellow", "Red"];
    const arr2 = ["Violet", "Pink"];
    const arrConcated = arr.concat(arr2); //new array with Values ["Black", "Green", "Yellow", "Red", "Violet", "Pink"], arr and arr2 remains unaffected
To search among elements:
  • indexOf/lastIndexOf(item, pos) – look for item starting from
    position pos, return the index or -1 if not found.
    Example:
    const arr = ["Black", "Green", "Yellow", "Red", "Green"];
    const found = arr.indexOf("Green"); //returns 1
    const foundLast = arr.indexOf("Green"); //returns 4 i.e the lastIndex
  • includes(value) – returns true if the array has value,
    otherwise false.
    Example:
    const arr = ["Black", "Green", "Yellow", "Red"];
    const found = arr.includes("Green"); //returns true
  • find/filter(func) – filter elements through the function, return first/all values that
    make it return true.
    Example:
    const arrAge = [15, 18, 21, 12];
    const arrFiltered = arrAge.filter(function(currentValue, index, arr){
    return currentValue > 15 }); //returns all ages greater than 18 i.e [18, 21]
    const intFind = arrAge.find(function(currentValue, index, arr){ return currentValue > 18 }); //returns the first age found greater than 18 i.e 21
  • findIndex –  is like find, but returns the index instead of a value.
    Example:
    const arrAge = [15, 18, 21, 12];
    const intIndexFound = arrAge.findIndex(function(currentValue, index, arr){ return currentValue > 15 }); //returns the first index of
    age found greater than 15 i.e 1
To iterate over elements:
  • forEach(func) – calls func for every element, does not return anything.
    Example:
    const arrAge = [15, 18, 21, 12];
    arrAge.forEach(function(item, index, arr){ arr[index] = item * 2; }); //[30,36,42,24]
To transform the array:
  • map(func) – creates a new array from results of calling func for every element.
    Example:
    let arr = [15, 18, 21, 12];
    arr = arr.map(int => { return int * 2 } );
    //[30,36,42,24]
  • sort(func) – sorts the array in-place, then returns it.
    Example:
    let arr = [15, 18, 21, 12];
    arr.sort((a, b) => (a > b ? -1 : 1));
    //[12,15,18,21]
  • reverse() – reverses the array in-place, then returns it.
    Example:
    let arr = [15, 18, 21, 12];
    arr.reverse(); //[12,21,18,15]
  • split/join – convert a string to array and back.
    Example:
    //split const str = "Hello There";
    const arr = str.split(" "); //returns ["Hello",
    "There"] //join
    const arr = [12,21,18,15]; arr.join() // Returns "12,21,18,15"
  • reduce/reduceRight(func, initial) – calculate a single value over the array by
    calling func for each element and passing an intermediate result between the calls.
Other Functions:
  • Array.isArray(arr) checks arr for being an array.

Please note that methods sortreverse and splice modify the array itself. These
methods are the most used ones, they cover 99% of use cases.

Categories
AWS Servers

How to add SSL on AWS Lightsail with LAMP Stack

If you are using Lightsail AWS Server with LAMP Stack deployed and are wondering how can i enable SSL for my domains, its very simple.

The Bitnami LAMP Stack comes with command line tools to enable SSL using Lets Encrypt.

To launch the Bitnami HTTPS Configuration Tool, execute the following command on SSH and follow the prompts:
sudo /opt/bitnami/bncert-tool

It will start an interactive command line session with simple questions to configure SSL for your domain.

Categories
Javascript VueJS

Vue Essentials Cheat Sheet

Attached cheatsheet from Vue Mastery that contains most common and essential documentation on VueJS.

Vue-Essentials-Cheat-Sheet