<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	
	xmlns:georss="http://www.georss.org/georss"
	xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"
	>

<channel>
	<title>Vuejs Archives - Program Easily</title>
	<atom:link href="https://programeasily.com/category/vuejs/feed/" rel="self" type="application/rss+xml" />
	<link>https://programeasily.com/category/vuejs/</link>
	<description>Program Easily helps people to learn about software programs in a easy manner.</description>
	<lastBuildDate>Thu, 15 Dec 2022 03:57:29 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.1</generator>

<image>
	<url>https://i0.wp.com/programeasily.com/wp-content/uploads/2020/12/cropped-logo.png?fit=32%2C32&#038;ssl=1</url>
	<title>Vuejs Archives - Program Easily</title>
	<link>https://programeasily.com/category/vuejs/</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">187075990</site>	<item>
		<title>When to use NextTick API in Vue.js</title>
		<link>https://programeasily.com/2022/12/15/when-to-use-nexttick-api-in-vue-js/</link>
					<comments>https://programeasily.com/2022/12/15/when-to-use-nexttick-api-in-vue-js/#respond</comments>
		
		<dc:creator><![CDATA[Admin]]></dc:creator>
		<pubDate>Thu, 15 Dec 2022 03:54:10 +0000</pubDate>
				<category><![CDATA[Vuejs]]></category>
		<category><![CDATA[vue]]></category>
		<category><![CDATA[vue.js]]></category>
		<category><![CDATA[vue3]]></category>
		<guid isPermaLink="false">https://programeasily.com/?p=2042</guid>

					<description><![CDATA[<p>NextTick is one of the cool feature in the VUE world. In Vue.js, When we change the state, it will not update/affect the DOM instantly or synchronously. Rather It will collect the state changes and do the DOM update once asynchronously no matter how many state changes you have made. NextTick API in Vue.js &#60;script&#62; import { nextTick } from 'vue' export default { data() { return { count: 0 } }, methods: { async increment() { this.count++ // DOM...</p>
<p class="read-more"><a class="btn btn-default" href="https://programeasily.com/2022/12/15/when-to-use-nexttick-api-in-vue-js/"> Read More<span class="screen-reader-text">  Read More</span></a></p>
<p>The post <a rel="nofollow" href="https://programeasily.com/2022/12/15/when-to-use-nexttick-api-in-vue-js/">When to use NextTick API in Vue.js</a> appeared first on <a rel="nofollow" href="https://programeasily.com">Program Easily</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><a href="https://vuejs.org/api/general.html#nexttick">NextTick</a> is one of the cool feature in the VUE world. In <a href="https://programeasily.com/vue/">Vue.js</a>, When we change the state, it will not update/affect the DOM instantly or synchronously. Rather It will collect the state changes and do the DOM update once asynchronously no matter how many state changes you have made.</p>
<p><img fetchpriority="high" decoding="async" class="size-full wp-image-2046" src="https://i0.wp.com/programeasily.com/wp-content/uploads/2022/12/Snapshot_58.png?resize=640%2C360&#038;ssl=1" alt="NextTick API" width="640" height="360" srcset="https://i0.wp.com/programeasily.com/wp-content/uploads/2022/12/Snapshot_58.png?w=1920&amp;ssl=1 1920w, https://i0.wp.com/programeasily.com/wp-content/uploads/2022/12/Snapshot_58.png?resize=300%2C169&amp;ssl=1 300w, https://i0.wp.com/programeasily.com/wp-content/uploads/2022/12/Snapshot_58.png?resize=1024%2C576&amp;ssl=1 1024w, https://i0.wp.com/programeasily.com/wp-content/uploads/2022/12/Snapshot_58.png?resize=768%2C432&amp;ssl=1 768w, https://i0.wp.com/programeasily.com/wp-content/uploads/2022/12/Snapshot_58.png?resize=1536%2C864&amp;ssl=1 1536w, https://i0.wp.com/programeasily.com/wp-content/uploads/2022/12/Snapshot_58.png?resize=480%2C270&amp;ssl=1 480w, https://i0.wp.com/programeasily.com/wp-content/uploads/2022/12/Snapshot_58.png?w=1280&amp;ssl=1 1280w" sizes="(max-width: 640px) 100vw, 640px" data-recalc-dims="1" /></p>
<h2>NextTick API in Vue.js</h2>
<pre><code class="language-javascript">&lt;script&gt;
import { nextTick } from 'vue'

export default {
  data() {
    return {
      count: 0
    }
  },
  methods: {
    async increment() {
      this.count++

      // DOM not yet updated
      console.log(document.getElementById('counter').textContent) // 0
    }
  }
}
&lt;/script&gt;

&lt;template&gt;
  &lt;button id="counter" @click="increment"&gt;{{ count }}&lt;/button&gt;
&lt;/template&gt;</code></pre>
<p>In the above program, we are changing the state of count by doing count++. But this will not update the DOM instantly rather the vue.js frameworks collects this information in the backend. After the whole execution of <code>increment()</code> method, It will update the DOM asynchronously.</p>
<p>But the problem is <code>document.getElementById('counter').textContent)</code> returns 0 in the <code>increment()</code> method. so if someone wants to use DOM element immediately, which is not possible in Vue.js directly. That&#8217;s where we have to use nextTick global API. <a href="https://v2.vuejs.org/v2/api/#Vue-nextTick" rel="noreferrer"><code>nextTick</code></a> allows you to execute code <em>after</em> you have changed some data and Vue.js has updated the virtual DOM based on your data change, but <em>before</em> the browser has rendered that change on the page.</p>
<p>We can pass the callback function to the <code>nextTick(callback(){})</code> which can be triggered after the successful DOM update. You can either pass a callback as an argument, or await the returned Promise.</p>
<pre><code class="language-javascript">import { nextTick } from 'vue'

export default {
  methods: {
    increment() {
      this.count++
      nextTick(() =&gt; {
        // access updated DOM
      })
    }
  }
}</code></pre>
<h2>Why Not SetTimeout ?</h2>
<p>Some people would think, why not <code>setTimeOut</code>!. We can also use <code>setTimeOut</code> But the problem is When you invoke <code>setTimeout</code>…</p>
<pre><code class="language-javascript">setTimeout(function() { 
    // access updated DOM
}, 100);</code></pre>
<p>then the browser would have a chance to update the page, and <em>then</em> your callback would get called. So the UI will render the old record first and then the new record will come. It&#8217;s not look good right. But with the help of <code>nextTick()</code> we can change the DOM value before being render into the screen. That&#8217;s the beauty of this API in Vue.js</p>
<h2>Summary</h2>
<p><code>nextTick()</code> can be used immediately after a state change to wait for the DOM updates to complete. We should not use <code>setTimeOut</code>to update the DOM rather should prefer <code>nextTick()</code></p>
<p>The post <a rel="nofollow" href="https://programeasily.com/2022/12/15/when-to-use-nexttick-api-in-vue-js/">When to use NextTick API in Vue.js</a> appeared first on <a rel="nofollow" href="https://programeasily.com">Program Easily</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://programeasily.com/2022/12/15/when-to-use-nexttick-api-in-vue-js/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2042</post-id>	</item>
		<item>
		<title>Pinia &#8211; The Vue Store Library</title>
		<link>https://programeasily.com/2022/08/23/pinia-the-vue-store-library/</link>
					<comments>https://programeasily.com/2022/08/23/pinia-the-vue-store-library/#respond</comments>
		
		<dc:creator><![CDATA[Admin]]></dc:creator>
		<pubDate>Tue, 23 Aug 2022 04:14:22 +0000</pubDate>
				<category><![CDATA[Vuejs]]></category>
		<category><![CDATA[pinia]]></category>
		<category><![CDATA[store]]></category>
		<category><![CDATA[vue]]></category>
		<category><![CDATA[vue3]]></category>
		<guid isPermaLink="false">https://programeasily.com/?p=688</guid>

					<description><![CDATA[<p>What is Pinia Pinia is a library store for Vue.js. It will work with Vue.js 3 as well as Vue.js 2. Pinia holds the state and business logic which is not bounded with component object trees. In other words, I would say it creates a global state where everybody can read and write the data. Pinia has three area&#8217;s as follows, State Getters Action We can assume and compare these things with data, computed and methods in components. Why Pinia...</p>
<p class="read-more"><a class="btn btn-default" href="https://programeasily.com/2022/08/23/pinia-the-vue-store-library/"> Read More<span class="screen-reader-text">  Read More</span></a></p>
<p>The post <a rel="nofollow" href="https://programeasily.com/2022/08/23/pinia-the-vue-store-library/">Pinia &#8211; The Vue Store Library</a> appeared first on <a rel="nofollow" href="https://programeasily.com">Program Easily</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h2>What is Pinia</h2>
<p><span style="font-weight: 400;"><a href="https://pinia.vuejs.org/">Pinia</a> is a library store for <a href="https://programeasily.com/vue/">Vue.js</a>. It will work with Vue.js 3 as well as Vue.js 2. Pinia holds the state and business logic which is not bounded with component object trees. In other words, <strong>I would say it creates a global state where everybody can read and write the data</strong>. Pinia has three area&#8217;s as follows,</span></p>
<ol>
<li>State</li>
<li>Getters</li>
<li>Action</li>
</ol>
<p><span style="font-weight: 400;">We can assume and compare these things with data, computed and methods in components.</span></p>
<p><img decoding="async" class="aligncenter wp-image-1625 size-full" src="https://i0.wp.com/programeasily.com/wp-content/uploads/2022/08/Snapshot_13.png?resize=640%2C360&#038;ssl=1" alt="Pinia Introduction" width="640" height="360" srcset="https://i0.wp.com/programeasily.com/wp-content/uploads/2022/08/Snapshot_13.png?w=1920&amp;ssl=1 1920w, https://i0.wp.com/programeasily.com/wp-content/uploads/2022/08/Snapshot_13.png?resize=300%2C169&amp;ssl=1 300w, https://i0.wp.com/programeasily.com/wp-content/uploads/2022/08/Snapshot_13.png?resize=1024%2C576&amp;ssl=1 1024w, https://i0.wp.com/programeasily.com/wp-content/uploads/2022/08/Snapshot_13.png?resize=768%2C432&amp;ssl=1 768w, https://i0.wp.com/programeasily.com/wp-content/uploads/2022/08/Snapshot_13.png?resize=1536%2C864&amp;ssl=1 1536w, https://i0.wp.com/programeasily.com/wp-content/uploads/2022/08/Snapshot_13.png?resize=480%2C270&amp;ssl=1 480w, https://i0.wp.com/programeasily.com/wp-content/uploads/2022/08/Snapshot_13.png?w=1280&amp;ssl=1 1280w" sizes="(max-width: 640px) 100vw, 640px" data-recalc-dims="1" /></p>
<h2 id="when-should-i-use-a-store" tabindex="-1">Why Pinia (A Store)</h2>
<p><span style="font-weight: 400;"><strong>Store will have the data that can be used everywhere in our application</strong>. Meanwhile we should avoid the local data in the store which can be added in the component instead. Pinia is a choice if your application needs to access the global state values.</span></p>
<h2>Features of Pinia</h2>
<ul>
<li>Hot module replacement
<ul>
<li>Modify your stores without reloading your page</li>
<li>Keep any existing state while developing</li>
</ul>
</li>
<li>Plugins: extend Pinia features with plugins</li>
<li>Proper TypeScript support or <strong>autocompletion</strong> for JS users</li>
<li>Server Side Rendering Support</li>
<li>Devtools support
<ul>
<li>A timeline to track actions, mutations</li>
<li>Stores appear in components where they are used</li>
<li>Time travel and easier debugging</li>
</ul>
</li>
</ul>
<h2>Full Tutorial</h2>
<h3>Installations</h3>
<p>You can install pinia with the help of NPM or Yarn as follows,</p>
<pre><code class="language-bash">npm install pinia
or
yarn add pinia</code></pre>
<h3>Inject Pinia with CreateApp</h3>
<p><span style="font-weight: 400;">Here we are going to have only one store for the application. So we have to create its instance and inject the same in VUE createApp. You can call it a root store.</span></p>
<pre><code class="language-javascript">import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'

const pinia = createPinia()
const app = createApp(App)

app.use(pinia)
app.mount('#app')</code></pre>
<p><span style="font-weight: 400;">So what createPinia does here ?. It creates the entity which holds the state for our application. And It&#8217;s global state where one can read and write as well. It has three concepts or property&#8217;s</span></p>
<ol>
<li>state</li>
<li>getters</li>
<li>actions</li>
</ol>
<p>(You can assume this three components with data, computed and methods)</p>
<h3>Create the Store</h3>
<p><span style="font-weight: 400;">First we need to create the store template. We can create a store template using defineStore() and it requires a unique name. We may use this template across our application.</span></p>
<pre><code class="language-javascript">import { defineStore } from 'pinia'

// useStore could be anything like useUser, useCart
// the first argument is a unique id of the store across your application
export const useStore = defineStore('main', {
  // other options...
})</code></pre>
<p><span style="font-weight: 400;">Second we need to use this store template inside the setup() function so that it will create the store. We have to call useStore() as follows,</span></p>
<pre><code class="language-javascript">import { useStore } from '@/stores/counter'

export default {
  setup() {
    const store = useStore()

    return {
      // you can return the whole store instance to use it in the template
      store,
    }
  },
}</code></pre>
<p><span style="font-weight: 400;">Once the store is created you can access its properties like state, getters and actions.</span></p>
<h3>State</h3>
<p>The state is the heart of the system. It is a function that returns the initial state of the application.</p>
<pre><code class="language-javascript">import { defineStore } from 'pinia'

const useStore = defineStore('storeId', {
  // arrow function recommended for full type inference
  state: () =&gt; {
    return {
      // all these properties will have their type inferred automatically
      counter: 0,
      name: 'Eduardo',
      isAdmin: true,
    }
  },
})</code></pre>
<p><span style="font-weight: 400;">We can access the store to read and write its data through store instance, and we can reset it to the initial state as well</span></p>
<pre><code class="language-javascript">const store = useStore()

store.counter++

store.$reset()</code></pre>
<h3>Getter</h3>
<p><span style="font-weight: 400;">We can define the getters property in defineStore() template. I would say, it is a replacement for computed values.</span></p>
<pre><code class="language-javascript">export const useStore = defineStore('main', {
  state: () =&gt; ({
    counter: 0,
  }),
  getters: {
    // automatically infers the return type as a number
    doubleCount(state) {
      return state.counter * 2
    },
    // the return type **must** be explicitly set
    doublePlusOne(): number {
      // autocompletion and typings for the whole store 
      return this.doubleCount + 1
    },
  },
})</code></pre>
<p><span style="font-weight: 400;">Then we can access and use the getters inside the template as follows,</span></p>
<pre><code class="language-javascript">&lt;template&gt;
  &lt;p&gt;Double count is {{ store.doubleCount }}&lt;/p&gt;
&lt;/template&gt;

&lt;script&gt;
export default {
  setup() {
    const store = useStore()

    return { store }
  },
}
&lt;/script&gt;</code></pre>
<h3>Actions</h3>
<p><span style="font-weight: 400;">Actions are the replacement for the methods. We can add our actions in the defineStore() template. Unlike getters, we can write </span><b>asynchronous </b><span style="font-weight: 400;">operations inside action. It will useful for creating API calls for our business logic</span></p>
<pre><code class="language-javascript">import { mande } from 'mande'

const api = mande('/api/users')

export const useUsers = defineStore('users', {
  state: () =&gt; ({
    userData: null,
    // ...
  }),

  actions: {
    async registerUser(login, password) {
      try {
        this.userData = await api.post({ login, password })
        showTooltip(`Welcome back ${this.userData.name}!`)
      } catch (error) {
        showTooltip(error)
        // let the form component display the error
        return error
      }
    },
  },
})</code></pre>
<h2>Summary</h2>
<ul>
<li>Pinia is a store library for Vue, it allows you to share a state across components/pages.</li>
<li>Compared to Vuex, Pinia provides a simpler API with less ceremony, offers Composition-API-style APIs, and most importantly, has solid type inference support when used with TypeScript.</li>
<li>The formula is Create the template -&gt; create the store with state, getters and actions and use across the application.</li>
</ul>
<p>The post <a rel="nofollow" href="https://programeasily.com/2022/08/23/pinia-the-vue-store-library/">Pinia &#8211; The Vue Store Library</a> appeared first on <a rel="nofollow" href="https://programeasily.com">Program Easily</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://programeasily.com/2022/08/23/pinia-the-vue-store-library/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">688</post-id>	</item>
		<item>
		<title>Props in Vue 3</title>
		<link>https://programeasily.com/2022/02/26/props-in-vue-3/</link>
					<comments>https://programeasily.com/2022/02/26/props-in-vue-3/#respond</comments>
		
		<dc:creator><![CDATA[Admin]]></dc:creator>
		<pubDate>Sat, 26 Feb 2022 18:04:59 +0000</pubDate>
				<category><![CDATA[Vuejs]]></category>
		<category><![CDATA[vue]]></category>
		<category><![CDATA[vue3]]></category>
		<guid isPermaLink="false">https://programeasily.com/?p=221</guid>

					<description><![CDATA[<p>In the HTML elements, we are having attributes. This attribute provides additional information about elements. Similarly, we are having props as attributes for Components in Vue.js. Props provides additional information about the components. But there is an important difference between HTML elements and Components Props. To clarify, props are reactive and follow one way data flow with its children. Vue.js components require explicit props declaration which it assumes as it&#8217;s attributes. Props are declared using the props option, export default...</p>
<p class="read-more"><a class="btn btn-default" href="https://programeasily.com/2022/02/26/props-in-vue-3/"> Read More<span class="screen-reader-text">  Read More</span></a></p>
<p>The post <a rel="nofollow" href="https://programeasily.com/2022/02/26/props-in-vue-3/">Props in Vue 3</a> appeared first on <a rel="nofollow" href="https://programeasily.com">Program Easily</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><span style="font-weight: 400;">In the HTML elements, we are having attributes. This attribute provides additional information about elements. Similarly, we are having props as attributes for Components in Vue.js. <strong>Props provides additional information about the components.</strong> But there is an important difference between HTML elements and Components Props. To clarify, props are reactive and follow one way data flow with its children. Vue.js components require explicit props declaration which it assumes as it&#8217;s attributes. Props are declared using the props option,</span></p>
<pre><code class="language-javascript">export default {
  props: ['foo'],
  created() {
    // props are exposed on `this`
    console.log(this.foo)
  }
}</code></pre>
<p>Let&#8217;s take a deep dive into that with this post. If you are not familiar with Vue.js components, You should read <a href="https://programeasily.com/2020/12/22/components-in-vue-3/">Components in Vue 3 </a> first.</p>
<p><img decoding="async" class="aligncenter size-full wp-image-870" src="https://i0.wp.com/programeasily.com/wp-content/uploads/2022/02/Props-in-Vue-3.jpg?resize=640%2C427&#038;ssl=1" alt="Props in Vue 3" width="640" height="427" srcset="https://i0.wp.com/programeasily.com/wp-content/uploads/2022/02/Props-in-Vue-3.jpg?w=1280&amp;ssl=1 1280w, https://i0.wp.com/programeasily.com/wp-content/uploads/2022/02/Props-in-Vue-3.jpg?resize=300%2C200&amp;ssl=1 300w, https://i0.wp.com/programeasily.com/wp-content/uploads/2022/02/Props-in-Vue-3.jpg?resize=1024%2C682&amp;ssl=1 1024w, https://i0.wp.com/programeasily.com/wp-content/uploads/2022/02/Props-in-Vue-3.jpg?resize=768%2C512&amp;ssl=1 768w, https://i0.wp.com/programeasily.com/wp-content/uploads/2022/02/Props-in-Vue-3.jpg?resize=405%2C270&amp;ssl=1 405w" sizes="(max-width: 640px) 100vw, 640px" data-recalc-dims="1" /></p>
<h2>One way data flow &#8211; Props in Vue 3</h2>
<p><span style="font-weight: 400;">Props follows one way data flow with it&#8217;s child component property. <strong>As a result, when we update the value of parent props, it will flow down and update the child property as well.</strong> At the same time it will not do vice versa. If you want to update the component state, the flow should start from the parent and all props in the child component will be refreshed with the latest value. We are having event emit concept to reverse back from child to parent in Vue.js.</span></p>
<pre><code class="language-javascript">export default {
  props: ['foo'],
  created() {
    // &#x274c; warning, props are readonly!
    this.foo = 'bar'
  }
}</code></pre>
<p>Suppose if you want to change the prop in the child component based on business scenario, you can transform the same using <a href="https://programeasily.com/2021/01/30/computed-in-vue-3/">computed in Vue.js</a></p>
<pre><code class="language-javascript">export default {
  props: ['size'],
  computed: {
    // computed property that auto-updates when the prop changes
    normalizedSize() {
      return this.size.trim().toLowerCase()
    }
  }
}</code></pre>
<h4>Note</h4>
<p><span style="font-weight: 400;">However, when passing arrays and objects as props, Vue.js will not prevent mutation of it&#8217;s nested properties. Because objects and arrays are passed by reference. Firstly, you should avoid such mutations as a best practice. Secondly, if you need this scenario in-deed, the child can emit an event and the parent listens to it and performs the mutation.</span></p>
<h2>Static and Dynamic Props</h2>
<p>The static props are nothing but just assign the static values like below,</p>
<pre><code class="language-markup">&lt;Blog title="I am a static prop example" /&gt;
</code></pre>
<p>You can also assign dynamic values to props with the help of  <code>v-bind</code> or its <code>:</code> like below</p>
<pre><code class="language-javascript">&lt;!-- Dynamically assign the value of a variable --&gt;
&lt;Blog v-bind:title="post.title"&gt;&lt;/Blog&gt;
// OR
&lt;Blog :title="post.title" &lt;/Blog&gt;</code></pre>
<h3>Passing other different values to prop</h3>
<p>We can pass Numbers, Boolean, Arrays as well as Object to a props value.</p>
<pre><code class="language-markup">// Number
&lt;!-- Even though `42` is static, we need v-bind to tell Vue that --&gt;
&lt;!-- this is a JavaScript expression rather than a string.  --&gt;
&lt;Blog :likes="42" /&gt;

&lt;!-- Dynamically assign to the value of a variable. --&gt;
&lt;Blog :likes="post.likes" /&gt;

// Boolean
&lt;!-- Including the prop with no value will imply `true`. --&gt;
&lt;Blog is-published /&gt;

&lt;!-- this is a JavaScript expression rather than a string. --&gt;
&lt;Blog :is-published="false" /&gt;

&lt;!-- Dynamically assign to the value of a variable. --&gt;
&lt;Blog :is-published="post.isPublished" /&gt;

// Array
&lt;!-- this is a JavaScript expression rather than a string. --&gt;
&lt;Blog :comment-ids="[234, 266, 273]" /&gt;

&lt;!-- Dynamically assign to the value of a variable. --&gt;
&lt;Blog :comment-ids="post.commentIds" /&gt;

// Object
&lt;!-- this is a JavaScript expression rather than a string. --&gt;
&lt;Blog
  :author="{
    name: 'Veronica',
    company: 'Veridian Dynamics'
  }"
 /&gt;

&lt;!-- Dynamically assign to the value of a variable. --&gt;
&lt;Blog :author="post.author" /&gt;</code></pre>
<h2>Validation &#8211; Props in Vue 3</h2>
<p><span style="font-weight: 400;">There are three ways of prop validations available in Vue.js. <strong>If the validation fails, then Vue.js will warn us in the browser&#8217;s JavaScript console.</strong> This is really needed to define the component and the application developers are aware of the intention of the component as well.</span></p>
<ol>
<li>Type validation</li>
<li>Mandatory or not (Required)</li>
<li>Custom validator</li>
</ol>
<pre><code class="language-javascript">export default {
  props: {
    // 1. Type Validation
    //  (`null` and `undefined` values will allow any type)
    propA: Number,
    // Multiple possible types
    propB: [String, Number],
    // 2. Mandatory validation with default value
    propC: {
      type: String,
      required: true,
      default: "Hello"
    },
    // 3. Custom validator
    propF: {
      validator(value) {
        // The value must match one of these strings
        return ['success', 'warning', 'danger'].includes(value)
      }
    }
  }
}</code></pre>
<h2>In setup Hook &#8211; Props in Vue 3</h2>
<p>The setup function is the entry point of the Composition API in Vue.js. The first argument of the setup function is the props argument. <strong>Props inside the setup function are reactive by nature.</strong></p>
<pre><code class="language-javascript">export default {
  props: {
    title: String
  },
  setup(props) {
    console.log(props.title)
  }
}</code></pre>
<p><span style="font-weight: 400;">If you destructor the props object, it will lose the reactivity. So we should avoid changing the props object there. But if you really need to destructor the props, you can go for</span><a href="https://vuejs.org/api/reactivity-utilities.html#torefs"> <span style="font-weight: 400;">toRefs()</span></a><span style="font-weight: 400;"> and </span><a href="https://vuejs.org/api/reactivity-utilities.html#toref"><span style="font-weight: 400;">toRef()</span></a><span style="font-weight: 400;"> API.</span></p>
<pre><code class="language-javascript">import { toRefs } from 'vue'

export default {
  setup(props) {
    // turn `props` into an object of refs, then destructure
    const { title } = toRefs(props)
    // `title` is a ref that tracks `props.title`
    console.log(title.value)

    // OR, turn a single property on `props` into a ref
    const title = toRef(props, 'title')
  }
}</code></pre>
<h2>Special Feature &#8211; Boolean Casting</h2>
<p>When we use Boolean props , <span style="font-weight: 400;">it has a</span> special casting rule. It is similar to the native Boolean attribute in any programming language. Let me show you with below example,</p>
<pre><code class="language-javascript">&lt;!-- equivalent of passing :disabled="true" --&gt;
&lt;MyComponent disabled /&gt;

&lt;!-- equivalent of passing :disabled="false" --&gt;
&lt;MyComponent /&gt;

// The casting rules for Boolean will apply regardless of type appearance order for below example as well
export default {
  props: {
    disabled: [Boolean, Number]
  }
}</code></pre>
<h2><strong>Name Casing in Props</strong></h2>
<p>When we declare props in Vue.js we have to follow camelCase. It will avoid to use quotes when we dealing them as property keys, and makes as valid JavaScript identifiers.</p>
<pre><code class="language-javascript">export default {
  props: {
    greetingMessage: String
  }
}
// using the “Mustache” syntax (double curly braces)
&lt;span&gt;{{ greetingMessage }}&lt;/span&gt;
</code></pre>
<p><span style="font-weight: 400;">So when we pass the props values to the child component , we can use camelCase. <strong>But Here the convention is kebab-case similar to the one below.</strong></span></p>
<pre><code class="language-javascript">&lt;MyComponent greeting-message="hello" /&gt;
</code></pre>
<h2>Summary</h2>
<p>In Conclusion,</p>
<ul>
<li style="font-weight: 400;" aria-level="1"><span style="font-weight: 400;">Firstly, <strong>we are having props as attributes for Components in Vue.js. Props provides additional information about the components.</strong></span></li>
<li style="font-weight: 400;" aria-level="1"><span style="font-weight: 400;">Secondly, props follows one way data flow with it&#8217;s child component property. <strong>When we update the value of parent props, it will flow down and update the child property as well.</strong> At the same time it will not vice versa.</span></li>
<li style="font-weight: 400;" aria-level="1"><span style="font-weight: 400;">In Vue.js 3, The first argument of the setup function is the props argument. <strong>Props inside the setup function are reactive by nature.</strong></span></li>
</ul>
<p>The post <a rel="nofollow" href="https://programeasily.com/2022/02/26/props-in-vue-3/">Props in Vue 3</a> appeared first on <a rel="nofollow" href="https://programeasily.com">Program Easily</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://programeasily.com/2022/02/26/props-in-vue-3/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">221</post-id>	</item>
		<item>
		<title>Custom Directives in Vue 3</title>
		<link>https://programeasily.com/2022/02/24/custom-directives-in-vue-3/</link>
					<comments>https://programeasily.com/2022/02/24/custom-directives-in-vue-3/#respond</comments>
		
		<dc:creator><![CDATA[Admin]]></dc:creator>
		<pubDate>Thu, 24 Feb 2022 09:55:16 +0000</pubDate>
				<category><![CDATA[Vuejs]]></category>
		<category><![CDATA[vue]]></category>
		<category><![CDATA[vue3]]></category>
		<guid isPermaLink="false">https://programeasily.com/?p=319</guid>

					<description><![CDATA[<p>In addition with default directive, we could also create and use custom directive in Vue.js. If you remember, firstly you can compare these directives with HTML Boolean attributes. Something similar to disabled attribute. The disabled attribute makes HTML element unusable and un-clickable. Ultimately it brings some execution on the elements. Similarly, The custom directive brings some execution on the relevant DOM elements. We can define custom directive as an object containing lifecycle hooks similar to those of a component. Below...</p>
<p class="read-more"><a class="btn btn-default" href="https://programeasily.com/2022/02/24/custom-directives-in-vue-3/"> Read More<span class="screen-reader-text">  Read More</span></a></p>
<p>The post <a rel="nofollow" href="https://programeasily.com/2022/02/24/custom-directives-in-vue-3/">Custom Directives in Vue 3</a> appeared first on <a rel="nofollow" href="https://programeasily.com">Program Easily</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In addition with default directive, we could also create and use custom directive in Vue.js. If you remember, firstly you can compare these directives with HTML Boolean attributes. Something similar to <code>disabled</code> attribute. The disabled attribute makes HTML element unusable and un-clickable. Ultimately it brings some execution on the elements. Similarly, The custom directive brings some execution on the relevant DOM elements. We can define custom directive as an object containing lifecycle hooks similar to those of a component. Below is the very simple use case,</p>
<pre><code class="language-javascript">const focus = {
  mounted: (el) =&gt; el.focus()
}

export default {
  directives: {
    // enables v-focus in template
    focus
  }
}</code></pre>
<p>We can use above directive in the template like below,</p>
<pre><code class="language-javascript">&lt;input v-focus /&gt;
</code></pre>
<p>This is a simple example, we can do lot more with this directives. But, here it will focus the input element assuming you haven&#8217;t clicked elsewhere on the page. Let&#8217;s take the deep dive into it.</p>
<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-862" src="https://i0.wp.com/programeasily.com/wp-content/uploads/2022/02/custom-directive-in-vue.jpg?resize=640%2C320&#038;ssl=1" alt="Custom Directives in Vue" width="640" height="320" srcset="https://i0.wp.com/programeasily.com/wp-content/uploads/2022/02/custom-directive-in-vue.jpg?w=1920&amp;ssl=1 1920w, https://i0.wp.com/programeasily.com/wp-content/uploads/2022/02/custom-directive-in-vue.jpg?resize=300%2C150&amp;ssl=1 300w, https://i0.wp.com/programeasily.com/wp-content/uploads/2022/02/custom-directive-in-vue.jpg?resize=1024%2C512&amp;ssl=1 1024w, https://i0.wp.com/programeasily.com/wp-content/uploads/2022/02/custom-directive-in-vue.jpg?resize=768%2C384&amp;ssl=1 768w, https://i0.wp.com/programeasily.com/wp-content/uploads/2022/02/custom-directive-in-vue.jpg?resize=1536%2C768&amp;ssl=1 1536w, https://i0.wp.com/programeasily.com/wp-content/uploads/2022/02/custom-directive-in-vue.jpg?resize=540%2C270&amp;ssl=1 540w, https://i0.wp.com/programeasily.com/wp-content/uploads/2022/02/custom-directive-in-vue.jpg?w=1280&amp;ssl=1 1280w" sizes="auto, (max-width: 640px) 100vw, 640px" data-recalc-dims="1" /></p>
<h2>Global Directive Registration</h2>
<p>In the above example, we are using local registration. In addition, similar to <a href="https://programeasily.com/2020/12/22/components-in-vue-3/">components</a>, we can globally register custom directives in the application instance. So that we can use the directives through out the application in the templates.</p>
<pre><code class="language-javascript">const app = createApp({})

// make v-focus usable in all components
app.directive('focus', {
  /* ... */
})</code></pre>
<p>However, we can prefer to use custom directives only when the desired functionality can only be achieved via direct DOM manipulation. Otherwise we could use v-bind because they are more efficient and server-rendering friendly.</p>
<h2 id="directive-hooks" tabindex="-1">Custom Directives in Vue 3 &#8211; Hooks</h2>
<p>The directive object is providing lot of optional hook functions. For Instance, we would use this hooks to manipulate the DOM, read the old value, component instance and vnode representation as well.</p>
<pre><code class="language-javascript">const myDir = {
  // called before bound element's attributes
  // or event listeners are applied
  created(el, binding, vnode, prevVnode) {
    // see below for details on arguments
  },
  // called right before the element is inserted into the DOM.
  beforeMount() {},
  // called when the bound element's parent component
  // and all its children are mounted.
  mounted() {},
  // called before the parent component is updated
  beforeUpdate() {},
  // called after the parent component and
  // all of its children have updated
  updated() {},
  // called before the parent component is unmounted
  beforeUnmount() {},
  // called when the parent component is unmounted
  unmounted() {}
  }
}</code></pre>
<h2 id="hook-arguments" tabindex="-1">Hook Arguments</h2>
<ul>
<li><strong>el</strong> &#8211; We can use el to manipulate the DOM</li>
<li><strong>binding</strong> &#8211; it is an object having lot of properties
<ul>
<li><strong>value</strong> &#8211; the value of the directive. Example, v-my-directive=&#8221;VALUE&#8221;</li>
<li><strong>oldValue</strong> &#8211; the old value of the directive. only available in <code>beforeUpdate</code> and <code>updated</code></li>
<li><strong>arg</strong> &#8211; the argument of the directive. Example, v-my-directive:foo</li>
<li><strong>instance</strong> &#8211; the instance of the component</li>
<li><strong>dir</strong> &#8211; the definition object of directive</li>
<li><strong>modifiers</strong> &#8211; the modifier object. Example v-my-directive:foo:bar. Here  the modifiers object would be <code>{ foo: true, bar: true }</code></li>
</ul>
</li>
<li>vnode &#8211; The V Node representation of the element</li>
<li>prevNode &#8211; The element of previous render. Only available in the <code>beforeUpdate</code> and <code>updated</code> hooks</li>
</ul>
<p>Consider the below example,</p>
<pre><code class="language-javascript">&lt;div v-example:foo.bar="baz"&gt;

// we can represent above directive as below object

{
  arg: 'foo',
  modifiers: { bar: true },
  value: /* value of `baz` */,
  oldValue: /* value of `baz` from previous update */
}

// binding value as JavaScript object literal

&lt;div v-demo="{ color: 'white', text: 'hello!' }"&gt;&lt;/div&gt;

app.directive('demo', (el, binding) =&gt; {
  console.log(binding.value.color) // =&gt; "white"
  console.log(binding.value.text) // =&gt; "hello!"
}</code></pre>
<h2>Dynamic Argument in Directives</h2>
<p>We can also pass dynamic argument to the directives. This is one of the special feature of directive. For example,</p>
<pre><code class="language-javascript">&lt;div v-example:[arg]="value"&gt;&lt;/div&gt;

// Here the directive argument will be reactively updated 
   based on arg property in our component state.</code></pre>
<p>Most important this here is , other than el, we should not modify other read-only properties. If you want so, you can follow this <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset">dataset</a></p>
<h2>Function Shorthand</h2>
<p>If we wants only <code>mounted</code> and <code>updated</code> behavior of custom directives, then we can use function shorthand there.</p>
<pre><code class="language-javascript">&lt;div v-color="color"&gt;&lt;/div&gt;

app.directive('color', (el, binding) =&gt; {
  // this will be called for both `mounted` and `updated`
  el.style.color = binding.value
})</code></pre>
<h2>Custom Directives in Vue 3 &#8211; on Component</h2>
<p>As similar to DOM elements, we can use custom directives on component as well. Here It will apply to a component root element. Note that, sometimes the component may have more than one root node. If so, it will ignore the directives and a warning will be shown. Above all, it is not preferable to use custom directives on component.</p>
<pre><code class="language-javascript">&lt;MyComponent v-demo="test" /&gt;

&lt;!-- template of MyComponent --&gt;

&lt;div&gt; &lt;!-- v-demo directive will be applied here --&gt;
  &lt;span&gt;My component content&lt;/span&gt;
&lt;/div&gt;</code></pre>
<h2>With Directives</h2>
<p>In Addition, we can apply custom directives to v-node using <code>withDirectives</code> as follows,</p>
<pre><code class="language-javascript">import { h, withDirectives } from 'vue'

// a custom directive
const pin = {
  mounted() { /* ... */ },
  updated() { /* ... */ }
}

// &lt;div v-pin:top.animate="200"&gt;&lt;/div&gt;
const vnode = withDirectives(h('div'), [
  [pin, 200, 'top', { animate: true }]
])</code></pre>
<h2>Summary</h2>
<p>In Conclusion,</p>
<ul>
<li>Firstly, the custom directive brings some execution on the elements. We can define custom directive as an object containing lifecycle hooks similar to those of a component.</li>
<li>Use custom directives only when the desired functionality can only be achieved via direct DOM manipulation.</li>
<li>You would pass dynamic argument to the directives. This is one of the special feature of directive.</li>
</ul>
<h2>References</h2>
<ul>
<li><a href="https://vuejs.org/guide/reusability/custom-directives.html#introduction">https://vuejs.org/guide/reusability/custom-directives.html#introduction</a></li>
<li><a href="https://vuejs.org/guide/extras/render-function.html#custom-directives">https://vuejs.org/guide/extras/render-function.html#custom-directives</a></li>
</ul>
<p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://programeasily.com/2022/02/24/custom-directives-in-vue-3/">Custom Directives in Vue 3</a> appeared first on <a rel="nofollow" href="https://programeasily.com">Program Easily</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://programeasily.com/2022/02/24/custom-directives-in-vue-3/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">319</post-id>	</item>
		<item>
		<title>Petite Vue Introduction with Example</title>
		<link>https://programeasily.com/2021/07/17/petite-vue-introduction-with-example/</link>
					<comments>https://programeasily.com/2021/07/17/petite-vue-introduction-with-example/#respond</comments>
		
		<dc:creator><![CDATA[Admin]]></dc:creator>
		<pubDate>Sat, 17 Jul 2021 18:25:15 +0000</pubDate>
				<category><![CDATA[Vuejs]]></category>
		<category><![CDATA[vue]]></category>
		<category><![CDATA[vuejs]]></category>
		<guid isPermaLink="false">https://programeasily.com/?p=446</guid>

					<description><![CDATA[<p>Petite Vue.js is a new one from the Vue.js team which mainly focuses on optimization. It is only 5kb in size. Here the small amount of interactions are only done with HTML elements. So the question is what is this and what it&#8217;s for ?. Petite Vue.js is a JavaScript library which creates the DOM based mutates in places. This will deal with the HTML elements directly similar to Alpine.js. It uses Vue.js template and reactivity modules to update the...</p>
<p class="read-more"><a class="btn btn-default" href="https://programeasily.com/2021/07/17/petite-vue-introduction-with-example/"> Read More<span class="screen-reader-text">  Read More</span></a></p>
<p>The post <a rel="nofollow" href="https://programeasily.com/2021/07/17/petite-vue-introduction-with-example/">Petite Vue Introduction with Example</a> appeared first on <a rel="nofollow" href="https://programeasily.com">Program Easily</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><span style="font-weight: 400;">Petite Vue.js is a new one from the Vue.js team which mainly focuses on optimization. It is only 5kb in size. Here the small amount of interactions are only done with HTML elements. So the question is what is this and what it&#8217;s for ?.</span></p>
<p><b>Petite Vue.js is a JavaScript library which creates the DOM based mutates in places.</b><span style="font-weight: 400;"> This will deal with the HTML elements directly similar to Alpine.js. It uses Vue.js template and reactivity modules to update the DOM elements dynamically when the data changes. So here in this <strong>Petite Vue Introduction with Example</strong> article we are going to look at more details and use cases of petite vue.js in detail. Let&#8217;s take a deep dive into it.</span></p>
<h2 style="text-align: center;">Petite Vue Introduction with Example</h2>
<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-496" src="https://i0.wp.com/programeasily.com/wp-content/uploads/2021/07/Petite-Vue-Introduction-with-Example-scaled.jpg?resize=640%2C360&#038;ssl=1" alt="Petite Vue Introduction with Example" width="640" height="360" srcset="https://i0.wp.com/programeasily.com/wp-content/uploads/2021/07/Petite-Vue-Introduction-with-Example-scaled.jpg?w=2560&amp;ssl=1 2560w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/07/Petite-Vue-Introduction-with-Example-scaled.jpg?resize=300%2C169&amp;ssl=1 300w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/07/Petite-Vue-Introduction-with-Example-scaled.jpg?resize=1024%2C576&amp;ssl=1 1024w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/07/Petite-Vue-Introduction-with-Example-scaled.jpg?resize=768%2C432&amp;ssl=1 768w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/07/Petite-Vue-Introduction-with-Example-scaled.jpg?resize=1536%2C864&amp;ssl=1 1536w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/07/Petite-Vue-Introduction-with-Example-scaled.jpg?resize=2048%2C1152&amp;ssl=1 2048w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/07/Petite-Vue-Introduction-with-Example-scaled.jpg?resize=480%2C270&amp;ssl=1 480w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/07/Petite-Vue-Introduction-with-Example-scaled.jpg?w=1280&amp;ssl=1 1280w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/07/Petite-Vue-Introduction-with-Example-scaled.jpg?w=1920&amp;ssl=1 1920w" sizes="auto, (max-width: 640px) 100vw, 640px" data-recalc-dims="1" /></p>
<p>Petite Vue.js available in CDN network. So we can take it from directly as follows,</p>
<pre><code class="language-http">&lt;html&gt;

&lt;script src="https://unpkg.com/petite-vue" defer init&gt;&lt;/script&gt;

&lt;!--process only below element (v-scope specfied elements) --&gt;
&lt;div v-scope="{ count: 0 }"&gt;
  {{ count }}
  &lt;button @click="count++"&gt;do increment&lt;/button&gt;
&lt;/div&gt;

&lt;/html&gt;</code></pre>
<p><span style="font-weight: 400;">In the above example, count is a reactive one. While you click the button, count changes( data changes ) and it updates the DOM. Reactivity achieved right !. Note that here we are using some more terms, that we described below,</span></p>
<ul>
<li style="font-weight: 400;" aria-level="1"><span style="font-weight: 400;">We are using defer to execute the script after the HTML parsing operations.</span></li>
<li style="font-weight: 400;" aria-level="1"><span style="font-weight: 400;"><code>init</code> plays a major role here. <code>init</code> is a custom element that tells petite vue.js to automatically mount the application. You can find this logic from </span><a href="https://github.com/vuejs/petite-vue/blob/main/src/index.ts#L9"><span style="font-weight: 400;"> </span><span style="font-weight: 400;">https://github.com/vuejs/petite-vue/blob/main/src/index.ts#L9</span></a></li>
<li style="font-weight: 400;" aria-level="1"><b><span style="font-weight: 400;"><code><strong>v-scope</strong></code> </span> will be used to denote the area where the petite vue.js controls the page. Petite Vue.js processes only the <span style="font-weight: 400;"><code><strong>v-scope</strong></code> </span>specified element with its child elements.</b></li>
</ul>
<h3>Without Auto Init</h3>
<p><span style="font-weight: 400;">In addition, if you don&#8217;t want the auto <code>init</code> , remove it from the script tag. But you have to do it manually to the end of the body as follows.</span></p>
<pre><code class="language-markup">&lt;script src="https://unpkg.com/petite-vue"&gt;&lt;/script&gt;
&lt;script&gt;
  PetiteVue.createApp().mount()
&lt;/script&gt;</code></pre>
<h2>Root Scope &#8211; Global Data Object</h2>
<p>We can pass the optional data object to <span style="font-weight: 400;"><code>createApp()</code> </span> function. This will act as a global data and available to all expressions.</p>
<pre><code class="language-markup">&lt;html&gt;

&lt;script src="https://unpkg.com/petite-vue"&gt;&lt;/script&gt;

&lt;!-- global data object passed to createApp available --&gt;
&lt;div v-scope&gt;
  &lt;p&gt;{{ name }}&lt;/p&gt;
  &lt;p&gt;{{ reverseName }}&lt;/p&gt;
  &lt;button @click="addNumber"&gt;Add Number to Name&lt;/button&gt;
&lt;/div&gt;

&lt;script&gt;
    PetiteVue.createApp({
    // available to all expressions and act as reactive data
    name: 'Program Easily',
    number: 0,
    // getters
    get reverseName() {
      return this.name.split("").reverse().join("");
    },
    // methods
    addNumber() {
      this.name = this.name + ' ' + this.number++
    }
  }).mount()

&lt;/script&gt;

&lt;/html&gt;</code></pre>
<p><span style="font-weight: 400;">In the above example, we are using variables, getters and methods as global data to all expressions. We can use these values inside <code>v-scope</code> elements. It will maintain reactivity, when you change the data, it will update the DOM elements. You can check the full working example below,</span></p>
<p><iframe style="width: 100%; height: 500px; border: 0; border-radius: 4px; overflow: hidden;" title="Petite Vue Examples" src="https://codesandbox.io/embed/petite-vue-examples-v21y4?fontsize=14&amp;hidenavigation=1&amp;initialpath=global-scope-petite.html&amp;theme=dark" sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"></iframe></p>
<h2>Create Components &#8211; Petite Vue Introduction with Example</h2>
<p><span style="font-weight: 400;">Creating components using Petite vue.js is a little bit different. We have to create a reusable function that will return the literal object. The returned object will be available as props inside the template. And you need to specify the template with the</span><i><span style="font-weight: 400;"> <code>$template</code> </span></i><span style="font-weight: 400;">key in the return object. There are two ways to provide the template value.</span></p>
<ol>
<li>Template String.</li>
<li>ID selector to template element.</li>
</ol>
<pre><code class="language-markup">&lt;html&gt;

&lt;script src="https://unpkg.com/petite-vue"&gt;&lt;/script&gt;

&lt;template id="pe-btn"&gt;
    &lt;div :style="{ margin: '8px'}"&gt;
        &lt;button :style="{ padding: '8px', color: color, fontSize: size + 'px' }"&gt; {{ label }} &lt;/button&gt;
    &lt;/div&gt;
&lt;/template&gt;

&lt;div v-scope :style="{ display: 'flex' , justifyContent: 'center'}"&gt;
&lt;div v-scope="peBtn({label: 'Red Button', color : 'red', size: '20'})"&gt;&lt;/div&gt;
&lt;div v-scope="peBtn({label: 'Green Button', color : 'green', size: '20'})"&gt;&lt;/div&gt;
&lt;div v-scope="peBtn({label: 'Yellow Button', color : 'yellow', size: '20'})"&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;script&gt;

// reusable function that will return the literal object
function peBtn(props){
    return {
        $template: "#pe-btn",
        label: props.label,
        color: props.color,
        size: props.size
    }
}

PetiteVue.createApp().mount()

&lt;/script&gt;

&lt;/html&gt;</code></pre>
<p><span style="font-weight: 400;">In the above example, we are creating the button component. The button component has three props namely label, color and size. Likewise you can create your own components with n number of props. When you wish to use your component you have to give <code>v-scope</code> attribute to the parent element. So that Petite Vue.js listen and process those elements. You can check the full working example below,</span></p>
<p><iframe style="width: 100%; height: 500px; border: 0; border-radius: 4px; overflow: hidden;" title="Petite Vue Examples" src="https://codesandbox.io/embed/petite-vue-examples-v21y4?fontsize=14&amp;hidenavigation=1&amp;initialpath=component-petite.html&amp;theme=dark" sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"></iframe></p>
<h2>Reactive Modules &#8211; Petite Vue Introduction with Example</h2>
<p><span style="font-weight: 400;">Already we have seen the <code>createApp()</code> module which is used to mount the application. In addition Petite Vue.js provides a reactive module ( from <code>@vue/reactivity</code> ). Using a reactive module, we can create a global store. The data inside this store will act as reactive data and available throughout the application. Let us check with below example,</span></p>
<pre><code class="language-markup">&lt;html&gt;
  &lt;script src="https://unpkg.com/petite-vue"&gt;&lt;/script&gt;
  &lt;!-- local data object --&gt;
  &lt;div
    v-scope="{ 
      localName: 'Local PE', 
      localNumber: 0,
      get reverseName() {
        return this.localName.split('').reverse().join('')
      },
      addNumber() {
        this.localName = this.localName + ' ' + this.localNumber++;
      },
     }"
  &gt;
    &lt;h2&gt;Global&lt;/h2&gt;
    &lt;!-- using global reactive data object --&gt;
    &lt;p&gt;Name : {{ store.globalName }}&lt;/p&gt;
    &lt;p&gt;Reverse Name : {{ store.reverseName }}&lt;/p&gt;
    &lt;button @click="store.addNumber"&gt;Add Number to Global Name&lt;/button&gt;
    &lt;h2&gt;Local&lt;/h2&gt;
    &lt;!-- using local reactive data object --&gt;
    &lt;p&gt;Name : {{ localName }}&lt;/p&gt;
    &lt;p&gt;Reverse Name : {{ reverseName }}&lt;/p&gt;
    &lt;button @click="addNumber"&gt;Add Number to Local Name&lt;/button&gt;
  &lt;/div&gt;
  &lt;script&gt;
    // global reactive store
    const store = PetiteVue.reactive({
      globalName: "Global PE",
      globalNumber: 0,
      // getters
      get reverseName() {
        return this.globalName.split("").reverse().join("");
      },
      // methods
      addNumber() {
        this.globalName = this.globalName + " " + this.globalNumber++;
      },
    });
    // pass reactive object to createApp, so that it will act as global store
    PetiteVue.createApp({ store }).mount();
  &lt;/script&gt;
&lt;/html&gt;</code></pre>
<p><span style="font-weight: 400;">In the above example, we are creating a global store using <code>reactive</code> objects. And we are creating local data objects using <code>v-scope</code> value. The global store data available throughout the application. At the same time, local data objects are accessible only inside the respective <code>v-scope</code> element. Here the state will maintain that <code>Add number to Global Name</code>  will change the global records. The same way <code>Add number to Local Name</code> will change the local records.  You can check the full working example,</span></p>
<p><iframe style="width: 100%; height: 500px; border: 0; border-radius: 4px; overflow: hidden;" title="Petite Vue Examples" src="https://codesandbox.io/embed/petite-vue-examples-v21y4?fontsize=14&amp;hidenavigation=1&amp;initialpath=reactive-petite.html&amp;theme=dark" sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"></iframe></p>
<h2>Summary</h2>
<ul>
<li>Petite Vue.js is a JavaScript library which creates the DOM based mutates in places.</li>
<li>It uses Vue.js template and reactivity modules to update the DOM elements dynamically when the data changes.</li>
<li><span style="font-weight: 400;"><code>v-scope</code></span> will be used to denote the area where the petite vue.js controls the page. Petite Vue.js <span style="font-weight: 400;">processes </span>the child elements only inside the <span style="font-weight: 400;"><code>v-scope</code></span> specified element.</li>
<li>Petite Vue.js provides a reactive module ( from <span style="font-weight: 400;"><code>@vue/reactivity</code></span>). Using a reactive module, we can create a global store.</li>
<li>And it&#8217;s a new one. So let&#8217;s wait and will see the full features of Petite vue.js</li>
</ul>
<h2>References</h2>
<ul>
<li><a href="https://github.com/vuejs/petite-vue">https://github.com/vuejs/petite-vue</a></li>
<li><a href="https://www.npmjs.com/package/petite-vue">https://www.npmjs.com/package/petite-vue</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://programeasily.com/2021/07/17/petite-vue-introduction-with-example/">Petite Vue Introduction with Example</a> appeared first on <a rel="nofollow" href="https://programeasily.com">Program Easily</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://programeasily.com/2021/07/17/petite-vue-introduction-with-example/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">446</post-id>	</item>
		<item>
		<title>Teleport in Vue 3 with Example</title>
		<link>https://programeasily.com/2021/07/13/teleport-in-vue-3-with-example/</link>
					<comments>https://programeasily.com/2021/07/13/teleport-in-vue-3-with-example/#respond</comments>
		
		<dc:creator><![CDATA[Admin]]></dc:creator>
		<pubDate>Tue, 13 Jul 2021 06:47:54 +0000</pubDate>
				<category><![CDATA[Vuejs]]></category>
		<category><![CDATA[vuejs]]></category>
		<category><![CDATA[vuejs3]]></category>
		<guid isPermaLink="false">https://programeasily.com/?p=321</guid>

					<description><![CDATA[<p>Creating the web pages using components is a good idea. So that we can re-use the logic and structure of the design. We have to make a component hierarchy or tree to make the UI better. In Vue.js we are using template string or render function to build the HTML DOM in the components. The Vue compiler will compile it and make the div elements for us However, sometimes logically, we need one component which could be a child to...</p>
<p class="read-more"><a class="btn btn-default" href="https://programeasily.com/2021/07/13/teleport-in-vue-3-with-example/"> Read More<span class="screen-reader-text">  Read More</span></a></p>
<p>The post <a rel="nofollow" href="https://programeasily.com/2021/07/13/teleport-in-vue-3-with-example/">Teleport in Vue 3 with Example</a> appeared first on <a rel="nofollow" href="https://programeasily.com">Program Easily</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><span style="font-weight: 400;">Creating the web pages using components is a good idea. So that we can re-use the logic and structure of the design. We have to make a component hierarchy or tree to make the UI better. In Vue.js we are using template string or render function to build the HTML DOM in the components. The Vue compiler will compile it and make the div elements for us</span></p>
<p><span style="font-weight: 400;">However, sometimes logically, we need one component which could be a child to its parent component, But the component HTML div should not be nest to its parent. Meanwhile we need to place it somewhere else in the DOM. Little bit confusing right.</span></p>
<p><span style="font-weight: 400;">Generally the HTML tree structure will be the same as component tree structure. But if you want to change one component div&#8217;s parent somewhere else in the DOM, we can go for teleport in Vue.js. It is an advanced feature introduced in Vue.js 3. If you are not familiar with Vue.js You can refer to our page</span><a href="https://programeasily.com/vue/"> <span style="font-weight: 400;">Vue</span></a><span style="font-weight: 400;"> Let&#8217;s go to the topic in detail.</span></p>
<p><img loading="lazy" decoding="async" class="aligncenter wp-image-466 size-large" src="https://i0.wp.com/programeasily.com/wp-content/uploads/2021/07/Teleport-in-Vue-3-with-Example-1.png?resize=640%2C535&#038;ssl=1" alt="Teleport in Vue 3 with Example" width="640" height="535" srcset="https://i0.wp.com/programeasily.com/wp-content/uploads/2021/07/Teleport-in-Vue-3-with-Example-1.png?resize=1024%2C856&amp;ssl=1 1024w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/07/Teleport-in-Vue-3-with-Example-1.png?resize=300%2C251&amp;ssl=1 300w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/07/Teleport-in-Vue-3-with-Example-1.png?resize=768%2C642&amp;ssl=1 768w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/07/Teleport-in-Vue-3-with-Example-1.png?resize=323%2C270&amp;ssl=1 323w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/07/Teleport-in-Vue-3-with-Example-1.png?w=1280&amp;ssl=1 1280w" sizes="auto, (max-width: 640px) 100vw, 640px" data-recalc-dims="1" /></p>
<h2>Teleport</h2>
<p><strong>Teleport will change the parent element of a component. Note that teleport will move actual DOM nodes instead of recreating it.</strong> This will maintain the same component instance. Teleport has two attributes.</p>
<ol>
<li>to &#8211; String</li>
<li>disabled &#8211; Boolean</li>
</ol>
<p><code>to</code> &#8211; <code>string</code> is <span style="font-weight: 400;">a prop denoting a target parent element where the teleport will move it&#8217;s content. It is a mandatory prop. This prop can be a valid query selector, or an HTML element (Example : body).</span></p>
<pre><code class="language-markup">&lt;teleport to="#to-parent-id" /&gt; 
&lt;teleport to=".to-parent-id" /&gt; 
&lt;teleport to="[to-parent-data-teleport]" /&gt;</code></pre>
<p><code>disabled</code> &#8211; <code>boolean</code> is a prop which disables the teleport operation. This is an optional Boolean prop. If we apply the disable prop, this will not move the teleport content to the target element. <strong>At the same time it will render the elements where you specified the teleport tag just like normal components.</strong> A great example for this use case is, streaming the video in either pop up or normally like below,</p>
<pre><code class="language-markup">&lt;teleport to="#popup" :disabled="popupOrInline"&gt;
  &lt;video src="./my-movie.mp4"&gt;
&lt;/teleport&gt;</code></pre>
<h2>Teleport in Vue 3 with Example</h2>
<p>Generally, we can achieve the same operation without teleport also. If we need to change the positions of the elements but quickly ,the process becomes difficult. But teleport makes the work simple for us. In our example, we are going to teleport a component to HTML  <code>#toPlace</code> div. Firstly we are creating Teleport component as follows</p>
<pre><code class="language-javascript">// TeleportComp.vue
&lt;template&gt;
  &lt;div&gt;
    &lt;teleport :to="teleportTo" :disabled="disableTeleport"&gt;
      &lt;TeleportChild:imagePath="imagePath" /&gt;
    &lt;/teleport&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
import TeleportChild from "./TeleportChild.vue";
export default {
  components: {
    TeleportChild,
  },
  props: {
    teleportTo: {
      type: String,
      default: "body",
    },
    imagePath: String,
    disableTeleport: Boolean,
  },
};
&lt;/script&gt;
</code></pre>
<p>Secondly we are creating the TeleportChild.vue component as follows,</p>
<pre><code class="language-javascript">// TeleportChild.vue
&lt;template&gt;
  &lt;img
    :src="imagePath"
    alt="Teleport child Text"
    :style="{ width: '100%', height: '100%' }"
  /&gt;
&lt;/template&gt;

&lt;script&gt;
export default {
  props: {
    imagePath: String,
    altText: String,
  },
};
&lt;/script&gt;</code></pre>
<p>In the above example,  we are using the child component <code>TeleportChild.vue</code> inside the Teleport Component. Note that here, logically <code>TeleportChild.vue</code> component will remain as child for <code>TeleportComp.vue</code> component even when it&#8217;s position changed (But actually not). Moreover the Vue.js Dev-tools also will have the same component hierarchy structure. Now we are creating the <code>TeleportDemo.vue</code> file to check the behaviors. Here we are enabling teleport operation based on <code>disableTeleport</code> flag.</p>
<pre><code class="language-javascript">// TeleportDemo.vue
&lt;template&gt;
  &lt;div id="toPlace"&gt;&lt;/div&gt;
  &lt;div :style="{ width: '200px', height: '200px' }"&gt;
    &lt;button class="btn" @click="onClickBtn"&gt;
      {{ disableTeleport ? "Move to toPlace" : "Come Back" }}
    &lt;/button&gt;
    &lt;TeleportComp
      teleportTo="#toPlace"
      imagePath="logo_transparent.png"
      :disableTeleport="disableTeleport"
    /&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
import { ref } from "vue";
import TeleportComp from "../components/teleport/TeleportComp.vue";
export default {
  components: {
    TeleportComp,
  },
  setup() {
    let disableTeleport = ref(true);
    const onClickBtn = () =&gt; {
      disableTeleport.value = !disableTeleport.value;
    };
    return {
      onClickBtn,
      disableTeleport,
    };
  },
};
&lt;/script&gt;
&lt;style scoped&gt;
#toPlace {
  width: 200px;
  height: 200px;
  margin: auto;
  display: flex;
  justify-content: center;
}
.btn {
  background-color: #4999f5;
  border: none;
  color: white;
  padding: 10px;
  font-size: 16px;
  cursor: pointer;
}
.btn:hover {
  background-color: #0417c0;
  color: white;
}
&lt;/style&gt;</code></pre>
<p>In the above example, if <code>disableTeleport</code> is set to true, then the teleport component acts as a normal component. if <code>disableTeleport</code> is set to false, the teleport component will be moved to <code>#toPlace</code> div element. Teleport will not change the hierarchy of component tree structure logically. But the effect will reflect in the HTML DOM. Now the image element moved to <code>#toPlace</code> element. You can check the full working example below,</p>
<p><iframe style="width: 100%; height: 500px; border: 0; border-radius: 4px; overflow: hidden;" title="vue-3-basics-program-easily" src="https://codesandbox.io/embed/github/programeasily/vue-3-basics/tree/main/?fontsize=14&amp;hidenavigation=1&amp;initialpath=teleportdemo&amp;module=%2Fsrc%2Fcomponents%2Fteleport%2FTeleportComp.vue&amp;theme=dark" sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"></iframe></p>
<h2>Multiple Teleport in Vue 3 with Example</h2>
<p>Now we are going to see multiple teleport operations. Here the same target element will have multiple teleport components. When we move the teleport components, It will follow the moving order and append to the target element.</p>
<pre><code class="language-javascript">&lt;teleport to="#toPlace"&gt;
  &lt;div&gt;A&lt;/div&gt;
&lt;/teleport&gt;
&lt;teleport to="#toPlace"&gt;
  &lt;div&gt;B&lt;/div&gt;
&lt;/teleport&gt;

&lt;!-- result--&gt;
&lt;div id="toPlace"&gt;
  &lt;div&gt;A&lt;/div&gt;
  &lt;div&gt;B&lt;/div&gt;
&lt;/div&gt;</code></pre>
<p>In the above example, the <code>#toPlace</code> element will have A,B div elements on teleport operation. Now we are creating <code>TeleportMultipleDemo.vue</code> file where we are moving two teleport components to same <code>#toPlace</code> target element. You can refer the full working example below</p>
<p><iframe style="width: 100%; height: 500px; border: 0; border-radius: 4px; overflow: hidden;" title="vue-3-basics-program-easily" src="https://codesandbox.io/embed/github/programeasily/vue-3-basics/tree/main/?fontsize=14&amp;hidenavigation=1&amp;initialpath=teleportmultipledemo&amp;module=%2Fsrc%2Fpage%2FTeleportMultipleDemo.vue&amp;theme=dark" sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"></iframe></p>
<h2>Summary</h2>
<ul>
<li><strong>Teleport will change the parent of a component. Note that teleport will move actual DOM nodes instead of recreating it.</strong></li>
<li style="text-align: left;">Even though teleport changes the parent elements, it will maintain the instances of components.</li>
<li>If disabled flag is given, it will render the elements where you specified the teleport tag just like normal components.</li>
<li>The same target element will have multiple teleport components.</li>
</ul>
<h2>Reference</h2>
<ul>
<li><a href="https://v3.vuejs.org/guide/teleport.html#teleport">https://v3.vuejs.org/guide/teleport.html#teleport</a></li>
<li><a href="https://v3.vuejs.org/api/built-in-components.html#teleport">https://v3.vuejs.org/api/built-in-components.html#teleport</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://programeasily.com/2021/07/13/teleport-in-vue-3-with-example/">Teleport in Vue 3 with Example</a> appeared first on <a rel="nofollow" href="https://programeasily.com">Program Easily</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://programeasily.com/2021/07/13/teleport-in-vue-3-with-example/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">321</post-id>	</item>
		<item>
		<title>Dynamic Component With Cloning Example Vue.js</title>
		<link>https://programeasily.com/2021/06/10/dynamic-component-with-cloning-example-vue-js/</link>
					<comments>https://programeasily.com/2021/06/10/dynamic-component-with-cloning-example-vue-js/#respond</comments>
		
		<dc:creator><![CDATA[Admin]]></dc:creator>
		<pubDate>Thu, 10 Jun 2021 18:39:49 +0000</pubDate>
				<category><![CDATA[Vuejs]]></category>
		<category><![CDATA[vuejs]]></category>
		<guid isPermaLink="false">https://programeasily.com/?p=316</guid>

					<description><![CDATA[<p>Nowadays, web developers prefer components to build the web pages effectively. Splitting the UI into reusable pieces is the goal of component creation. Each component will render specific predefined HTML design. There is no problem when the component is static. But sometimes based on condition or scenario, we have to render different components dynamically. To achieve this without using routing, Vue.js provides a special feature for us &#8211; Dynamic Components. Let&#8217;s take a deep dive to understand it clearly. If you...</p>
<p class="read-more"><a class="btn btn-default" href="https://programeasily.com/2021/06/10/dynamic-component-with-cloning-example-vue-js/"> Read More<span class="screen-reader-text">  Read More</span></a></p>
<p>The post <a rel="nofollow" href="https://programeasily.com/2021/06/10/dynamic-component-with-cloning-example-vue-js/">Dynamic Component With Cloning Example Vue.js</a> appeared first on <a rel="nofollow" href="https://programeasily.com">Program Easily</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Nowadays, web developers prefer components to build the web pages effectively. Splitting the UI into reusable pieces is the goal of component creation. Each component will render specific predefined HTML design. There is no problem when the component is static.</p>
<p>But sometimes based on condition or scenario, <strong>we have to render different components dynamically</strong>. To achieve this without using routing, Vue.js provides a special feature for us <strong>&#8211; Dynamic Components</strong>. Let&#8217;s take a deep dive to understand it clearly. If you are new to Vue.js Component topics, you can read about <a href="https://programeasily.com/2020/12/22/components-in-vue3/" target="_blank" rel="noopener">Components in Vue 3</a> and <a href="https://programeasily.com/2020/12/31/single-file-components-vue-3/" target="_blank" rel="noopener">Single File Components Vue 3</a> before moving to this session.</p>
<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-362" src="https://i0.wp.com/programeasily.com/wp-content/uploads/2021/06/Dynamic-Component-With-Cloning-Example-Vue.js.jpg?resize=640%2C439&#038;ssl=1" alt="Dynamic Component With Cloning Example Vue.js" width="640" height="439" srcset="https://i0.wp.com/programeasily.com/wp-content/uploads/2021/06/Dynamic-Component-With-Cloning-Example-Vue.js.jpg?w=1920&amp;ssl=1 1920w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/06/Dynamic-Component-With-Cloning-Example-Vue.js.jpg?resize=300%2C206&amp;ssl=1 300w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/06/Dynamic-Component-With-Cloning-Example-Vue.js.jpg?resize=1024%2C702&amp;ssl=1 1024w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/06/Dynamic-Component-With-Cloning-Example-Vue.js.jpg?resize=768%2C527&amp;ssl=1 768w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/06/Dynamic-Component-With-Cloning-Example-Vue.js.jpg?resize=1536%2C1054&amp;ssl=1 1536w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/06/Dynamic-Component-With-Cloning-Example-Vue.js.jpg?resize=394%2C270&amp;ssl=1 394w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/06/Dynamic-Component-With-Cloning-Example-Vue.js.jpg?w=1280&amp;ssl=1 1280w" sizes="auto, (max-width: 640px) 100vw, 640px" data-recalc-dims="1" /></p>
<h2>Dynamic Component With Cloning Example Vue.js</h2>
<p>In the below example, we can dynamically change the component. Here the old component will unmount and the new component will mount when the changes are made.</p>
<pre><code class="language-markup">&lt;!-- Syntax --&gt;
&lt;!-- component changes when componentName changes --&gt;
&lt;component :is="componentName"&gt;&lt;/component&gt;</code></pre>
<p><strong>We have to use  <code>is</code> attribute with <code>component</code> tag to achieve dynamic component features in Vue.js.</strong> Note that, here when we change the <code>componentName</code> the new component will render.</p>
<h2>Dynamic Component With Native HTML elements</h2>
<p>We can use <code>is</code> attribute with native HTML elements. When we bind an element to <code>is</code> attribute, it will render the HTML element in the DOM.</p>
<pre><code class="language-markup">&lt;component :is="'button'"&gt;This is Button&lt;/component&gt;
// This will show a button</code></pre>
<p>In addition, we can use the Vue.js component inside the HTML element using <code>is</code> attribute. In the below example, we are using <code>my-row</code> component inside the table HTML element</p>
<pre><code class="language-markup">&lt;table&gt;
  &lt;tr is="vue:my-row"&gt;&lt;/tr&gt;
&lt;/table&gt;</code></pre>
<h2>keep-alive with Dynamic Component</h2>
<p>Sometimes when we switch the components, we need to maintain the old component state or need to avoid the re-render process. Which means, we want to cache the component states. To achieve this, Vue.js provides a <strong>keep-alive</strong> feature. We can use it as below to cache the component states,</p>
<pre><code class="language-markup">&lt;!-- components will be cached! --&gt;
&lt;keep-alive&gt;
  &lt;component :is="componentName"&gt;&lt;/component&gt;
&lt;/keep-alive&gt;</code></pre>
<h2>Dynamic Component With Cloning Example Vue.js</h2>
<p>Generally in Vue.js we can use a <code>for</code> loop to clone a single component. Dynamic components along with a for loop helps us to clone different types of components at a go. Firstly we are going to create components for button, input and text-area.</p>
<h3>DcButton.vue</h3>
<pre><code class="language-javascript">&lt;template&gt;
  &lt;button class="btn"&gt;
    {{ label }}
  &lt;/button&gt;
&lt;/template&gt;

&lt;script&gt;
export default {
  props: {
    label: {
      type: String,
      default: "Default",
    },
  },
  setup() {
    return {};
  },
};
&lt;/script&gt;

&lt;style scoped&gt;
.btn {
  background-color: #4999f5;
  border: none;
  color: white;
  padding: 10px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 2px 2px;
  cursor: pointer;
}
.btn:hover {
  background-color: #0417c0;
  color: white;
}
&lt;/style&gt;</code></pre>
<h3>DcInput.vue</h3>
<pre><code class="language-bash">&lt;template&gt;
  &lt;div&gt;
    &lt;input
      type="text"
      class="input"
      v-model="value"
      :placeholder="placeHolderLabel"
    /&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
export default {
  props: {
    placeHolderLabel: {
      type: String,
      default: "Enter the value",
    },
  },
  data() {
    return {
      value: "",
    };
  },
};
&lt;/script&gt;

&lt;style scoped&gt;
.input {
  width: 200px;
  padding: 12px 20px;
  margin: 8px 0;
  display: inline-block;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
}
&lt;/style&gt;</code></pre>
<h3>DcTextArea.vue</h3>
<pre><code class="language-javascript">&lt;template&gt;
  &lt;div&gt;
    &lt;textarea
      v-model="value"
      rows="3"
      cols="3"
      class="input"
      :placeholder="placeHolderLabel"
    /&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
export default {
  props: {
    placeHolderLabel: {
      type: String,
      default: "Enter the value",
    },
  },
  data() {
    return {
      value: "",
    };
  },
};
&lt;/script&gt;

&lt;style scoped&gt;
.input {
  width: 200px;
  padding: 12px 20px;
  margin: 8px 0;
  display: inline-block;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
}
&lt;/style&gt;</code></pre>
<p>Secondly, we are going to create a dynamic component using the <code>component</code> tag. Note that, here we have two props namely <code>componentName</code>, <code>componentProps</code>. <strong>So whenever we pass the component name to this component it will render the specific component.</strong> We can also provide <code>props</code> for our component at runtime. So let&#8217;s do it.</p>
<h3>DynamicComp.vue</h3>
<pre><code class="language-javascript">&lt;template&gt;
  &lt;component :is="componentName" v-bind="componentProps"&gt;&lt;/component&gt;
&lt;/template&gt;
&lt;script&gt;
export default {
  props: {
    componentName: String,
    componentProps: Object,
  },
};
&lt;/script&gt;</code></pre>
<p>Since we are going to use input and text area components dynamically, we have to add the same with app component in main.js as follows,</p>
<pre><code class="language-javascript">import { createApp } from "vue";
import router from "./router/router.js";
import App from "./App.vue";
import dcInput from "./components/dynamic-comp/DcInput"
import dcTextArea from "./components/dynamic-comp/DcTextArea"

let app = createApp(App);
app.component("dcInput",dcInput)
app.component("dcTextArea",dcTextArea)

app.use(router).mount("#app");</code></pre>
<p>Now we are going to use the above components to create a simple cloning example. Here we are using two methods namely <code>addInput</code>, <code>addTextArea</code> to add input and text area components respectively.</p>
<h3>DyanamicComponentDemo.vue</h3>
<pre><code class="language-javascript">&lt;template&gt;
  &lt;h1&gt;Simple Cloning Component Example&lt;/h1&gt;
  &lt;div class="grp"&gt;
    &lt;dcButton label="Add Input" @click="addInput" /&gt;
    &lt;dcButton label="Add Text Area" @click="addTextArea" /&gt;
  &lt;/div&gt;
  &lt;dynamicComp
    v-for="(item, index) in items"
    :key="index"
    :componentName="item.componentName"
    :componentProps="item.componentProps"
  &gt;
  &lt;/dynamicComp&gt;
&lt;/template&gt;

&lt;script&gt;
import { ref } from "@vue/reactivity";
import dynamicComp from "../components/dynamic-comp/DynamicComp.vue";
import dcButton from "../components/dynamic-comp/DcButton.vue";
export default {
  components: {
    dynamicComp,
    dcButton,
  },
  setup() {
    let items = ref([]);
    const addInput = () =&gt; {
      items.value.push({
        componentName: "dcInput",
        componentProps: {
          placeHolderLabel: "Cloning Input",
        },
      });
    };
    const addTextArea = () =&gt; {
      items.value.push({
        componentName: "dcTextArea",
        componentProps: {
          placeHolderLabel: "Cloning Text Arae",
        },
      });
    };
    return {
      items,
      addInput,
      addTextArea,
    };
  },
};
&lt;/script&gt;

&lt;style scoped&gt;
.grp {
  padding-left: 408px;
}
&lt;/style</code></pre>
<p>In the above example, we are using a dynamic component with a <code>for</code> loop to clone different components. <strong>so whenever we update the items, it will create the new component dynamically</strong>. The thing is we have to push the component name and props to items as we did in addInput, addTextArea methods. You can find the full working example below,</p>
<h2>Dynamic Component With Cloning Example Vue.js</h2>
<h2><iframe style="width: 100%; height: 500px; border: 0; border-radius: 4px; overflow: hidden;" title="vue-3-basics-program-easily" src="https://codesandbox.io/embed/github/programeasily/vue-3-basics/tree/main/?fontsize=14&amp;hidenavigation=1&amp;initialpath=dynamicComponentDemo&amp;theme=dark" sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"></iframe></h2>
<h2>Full Sources</h2>
<ul>
<li><a href="https://github.com/programeasily/vue-3-basics/tree/main/src/components/dynamic-comp">https://github.com/programeasily/vue-3-basics/tree/main/src/components/dynamic-comp</a></li>
<li><a href="https://github.com/programeasily/vue-3-basics/blob/main/src/page/DynamicComponentDemo.vue">https://github.com/programeasily/vue-3-basics/blob/main/src/page/DynamicComponentDemo.vue</a></li>
</ul>
<h2>Reference</h2>
<ul>
<li><a href="https://v3.vuejs.org/guide/list.html#mapping-an-array-to-elements-with-v-for">https://v3.vuejs.org/guide/list.html#mapping-an-array-to-elements-with-v-for</a></li>
<li><a href="https://v3.vuejs.org/api/special-attributes.html#is">https://v3.vuejs.org/api/special-attributes.html#is</a></li>
<li><a href="https://v3.vuejs.org/guide/component-dynamic-async.html#dynamic-components-with-keep-alive">https://v3.vuejs.org/guide/component-dynamic-async.html#dynamic-components-with-keep-alive</a></li>
</ul>
<h2>Summary</h2>
<ul>
<li>We can render different components dynamically using component tag.</li>
<li>The old component will unmount and the new component will mount when the changes are made.</li>
<li>when we bind HTML elements to <code>is</code> attribute in the component tag, it will render the same in the DOM.</li>
<li>We can use dynamic components with a <code>for</code> loop to clone different types of components at a go.</li>
</ul>
<p>The post <a rel="nofollow" href="https://programeasily.com/2021/06/10/dynamic-component-with-cloning-example-vue-js/">Dynamic Component With Cloning Example Vue.js</a> appeared first on <a rel="nofollow" href="https://programeasily.com">Program Easily</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://programeasily.com/2021/06/10/dynamic-component-with-cloning-example-vue-js/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">316</post-id>	</item>
		<item>
		<title>Template Refs in Vue.js</title>
		<link>https://programeasily.com/2021/05/22/template-refs-in-vue-js/</link>
					<comments>https://programeasily.com/2021/05/22/template-refs-in-vue-js/#respond</comments>
		
		<dc:creator><![CDATA[Admin]]></dc:creator>
		<pubDate>Sat, 22 May 2021 17:41:54 +0000</pubDate>
				<category><![CDATA[Vuejs]]></category>
		<category><![CDATA[vue3]]></category>
		<category><![CDATA[vuejs]]></category>
		<guid isPermaLink="false">https://programeasily.com/?p=284</guid>

					<description><![CDATA[<p>Sometimes while creating components, we need to access its child components or child HTML elements directly in the JavaScript. Though we are having props and events for creating communication with child components, Vue.js provides the special attribute ref. We can create a reference variable using the ref attribute for child components/elements. During the virtual DOM mounting process, if the V-Node(HTML element or child component) has a ref attribute then the respected element or component instance will be stored under the...</p>
<p class="read-more"><a class="btn btn-default" href="https://programeasily.com/2021/05/22/template-refs-in-vue-js/"> Read More<span class="screen-reader-text">  Read More</span></a></p>
<p>The post <a rel="nofollow" href="https://programeasily.com/2021/05/22/template-refs-in-vue-js/">Template Refs in Vue.js</a> appeared first on <a rel="nofollow" href="https://programeasily.com">Program Easily</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Sometimes while creating components, we need to access its child components or child HTML elements directly in the JavaScript. Though we are having props and events for creating communication with child components, Vue.js provides the special attribute <code>ref</code>. We can create a reference variable using the <code>ref</code> attribute for child components/elements.</p>
<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-290" src="https://i0.wp.com/programeasily.com/wp-content/uploads/2021/05/Template-Refs-in-Vue.js.jpg?resize=640%2C396&#038;ssl=1" alt="Template Refs in Vue.js" width="640" height="396" srcset="https://i0.wp.com/programeasily.com/wp-content/uploads/2021/05/Template-Refs-in-Vue.js.jpg?w=1920&amp;ssl=1 1920w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/05/Template-Refs-in-Vue.js.jpg?resize=300%2C186&amp;ssl=1 300w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/05/Template-Refs-in-Vue.js.jpg?resize=1024%2C634&amp;ssl=1 1024w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/05/Template-Refs-in-Vue.js.jpg?resize=768%2C475&amp;ssl=1 768w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/05/Template-Refs-in-Vue.js.jpg?resize=1536%2C950&amp;ssl=1 1536w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/05/Template-Refs-in-Vue.js.jpg?resize=436%2C270&amp;ssl=1 436w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/05/Template-Refs-in-Vue.js.jpg?w=1280&amp;ssl=1 1280w" sizes="auto, (max-width: 640px) 100vw, 640px" data-recalc-dims="1" /></p>
<p>During the virtual DOM mounting process, if the V-Node(HTML element or child component) has a <code>ref</code> attribute then the respected element or component instance will be stored under the parent component&#8217;s <code>$refs</code>. Let’s take a deep dive into this with an example. Read <a href="https://programeasily.com/2020/12/22/components-in-vue3/" target="_blank" rel="noopener">Components in Vue3</a> and <a href="https://programeasily.com/2020/12/31/single-file-components-vue-3/" target="_blank" rel="noopener">Single File Components Vue 3</a> if you are new to Vue.js components.</p>
<h2>Template Refs in Vue.js</h2>
<p>We can use <code>ref</code> to create the reference for the element or child component. If <code>ref</code> is used on the HTML DOM element then the reference is mapped to the respected element. If <code>ref</code> is used on the child component, then the reference is mapped to the component instance. The parent component <code>$refs</code> object, stores the ref reference.</p>
<ul>
<li>Attribute Name : <code>ref</code></li>
<li>Expects : string or function</li>
<li>Example : &lt;input ref=&#8221;inputId&#8221; /&gt;</li>
</ul>
<h3>Example</h3>
<pre><code class="language-markup">&lt;!-- vm.$refs.p will be the HTML DOM element  --&gt;
&lt;p ref="p"&gt;hello to program easily&lt;/p&gt;

&lt;!-- vm.$refs.child will be the child component instance --&gt;
&lt;child-component ref="child"&gt;&lt;/child-component&gt;

&lt;!-- When bound dynamically, we can define ref as a callback function, 
passing the element or component instance explicitly --&gt;
&lt;child-component :ref="(el) =&gt; child = el"&gt;&lt;/child-component&gt;</code></pre>
<p>However <code>ref</code> registration timing is very important. Firstly these <span style="font-weight: 400;">processes </span> are done after the component render operation. So we can not access it on the initial render. Secondly we can not use <code>$refs</code> inside the template and data binding since it is not reactive. Now we are going to create the base-input component and use <code>ref</code> as follows,</p>
<p><iframe style="width: 100%; height: 500px; border: 0; border-radius: 4px; overflow: hidden;" title="template-refs-programeasily" src="https://codesandbox.io/embed/github/programeasily/template-refs-example-vue/tree/main/?fontsize=14&amp;hidenavigation=1&amp;theme=dark&amp;;view=split" sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"><span data-mce-type="bookmark" style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" class="mce_SELRES_start">﻿</span><span data-mce-type="bookmark" style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" class="mce_SELRES_start">﻿</span><span data-mce-type="bookmark" style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" class="mce_SELRES_start">﻿</span></iframe></p>
<p>In the above example, we need to call the updateInput method in the <code>onMounted</code> hook. Here the input element is available. We can access them using <code>this.$refs.input</code>. We have to add the input-comp in the index.html like below.</p>
<pre><code class="language-markup">&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;Parcel Sandbox&lt;/title&gt;
    &lt;meta charset="UTF-8" /&gt;
    &lt;script src="https://unpkg.com/vue@next"&gt;&lt;/script&gt;
  &lt;/head&gt;

  &lt;body&gt;
    &lt;div id="app"&gt;
      &lt;input-comp /&gt;
    &lt;/div&gt;

    &lt;script src="src/index.js"&gt;&lt;/script&gt;
  &lt;/body&gt;
&lt;/html&gt;
</code></pre>
<h2>Template Refs in Vue.js &#8211; Composition API</h2>
<p><strong>We can integrate the two concepts Template Refs and Reactive Refs in the Composition API.</strong> Generally we are using <code>$refs</code> to access the component instance/element. But here we can access the component instance/element with the help of reactive <code>ref</code>.</p>
<pre><code class="language-javascript">&lt;template&gt;
  &lt;div ref="root"&gt;Welcome to ProgramEasily&lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
  import { ref, onMounted } from 'vue';

  export default {
    setup() {
      const root = ref(null);

      onMounted(() =&gt; {
        // the DOM element will be assigned to the ref after initial render
        console.log(root.value) // &lt;div&gt;Welcome to ProgramEasily &lt;/div&gt;
      });

      return {
        root
      }
    }
  }
&lt;/script&gt;
</code></pre>
<p>In the above example, root is the reactive <code>ref</code> object which returned from the setup function. During the Virtual DOM mount operation, if the V-Node key matches with the <code>ref</code> of the render context, then the component instance/element is assigned to the value of the <code>ref</code>. In detail here,</p>
<ul>
<li>V-Node : &lt;div ref=&#8221;root&#8221;&gt;Welcome to ProgramEasily&lt;/div&gt;</li>
<li>V-Node key : root (ref=&#8221;root&#8221;)</li>
<li>ref of the render context : i.e. return from the setup function(const root = ref(null))</li>
</ul>
<p>Indeed, V-Node key root matches with <code>ref</code> of the render context. So we can access the element after the initial render. We can get the element in the <code>onMounted</code> <span style="font-weight: 400;">Lifecycle </span> hook like in the example.</p>
<h2 id="watching-template-refs">Template Refs &#8211; Watching</h2>
<p><code>watch</code> and <code>watchEffect</code> are run before the <code>onMounted</code> <span style="font-weight: 400;">Lifecycle </span> hook. But the DOM element will be available in the mounted phase. The result is template ref element not available on the watch operation. Refer the below example, here the root.value is null.</p>
<pre><code class="language-javascript">&lt;template&gt;
  &lt;div ref="root"&gt;Welcome to ProgramEasily&lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
  import { ref, watchEffect } from 'vue';

  export default {
    setup() {
      const root = ref(null);

      watchEffect(() =&gt; {
        // called before the DOM is mounted or updated
        console.log(root.value) // =&gt; null
      })

      return {
        root
      }
    }
  }
&lt;/script&gt;</code></pre>
<p>To solve this problem, Vue.js provides another option <code>flush: 'post</code>. This will execute the watch effect after the DOM element mount/update operation. So that the V-Node key root matches with <code>ref</code> of the render context and we can get the result as follows,</p>
<pre><code class="language-javascript">&lt;template&gt;
  &lt;div ref="root"&gt;Welcome to ProgramEasily&lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
  import { ref, watchEffect } from 'vue';

  export default {
    setup() {
      const root = ref(null);

      watchEffect(() =&gt; {
        console.log(root.value) // =&gt; &lt;div&gt;...&lt;/div&gt;
      }, 
      {
        flush: 'post'
      });

      return {
        root
      }
    }
  }
&lt;/script&gt;</code></pre>
<h2>References</h2>
<ul>
<li><a href="https://v3.vuejs.org/guide/component-template-refs.html">https://v3.vuejs.org/guide/component-template-refs.html</a></li>
<li><a href="https://v3.vuejs.org/guide/composition-api-template-refs.html#template-refs">https://v3.vuejs.org/guide/composition-api-template-refs.html#template-refs</a></li>
<li><a href="https://v3.vuejs.org/api/special-attributes.html#ref">https://v3.vuejs.org/api/special-attributes.html#ref</a></li>
</ul>
<h2>Summary</h2>
<ul>
<li>Template <code>refs</code> used to create the references for the element or child component.</li>
<li>The parent component <code>$refs</code> object, stores the <code>ref</code> reference.</li>
<li>In the Composition API, Template <code>refs</code> matched to Reactive <code>refs</code> in the Virtual DOM mount operation.</li>
<li>When we watch Template <code>refs</code>, we have to add <code>flush: 'post</code> to watch the <code>ref</code> after the DOM updated.</li>
</ul>
<p>The post <a rel="nofollow" href="https://programeasily.com/2021/05/22/template-refs-in-vue-js/">Template Refs in Vue.js</a> appeared first on <a rel="nofollow" href="https://programeasily.com">Program Easily</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://programeasily.com/2021/05/22/template-refs-in-vue-js/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">284</post-id>	</item>
		<item>
		<title>Lifecycle hooks in Vue 3</title>
		<link>https://programeasily.com/2021/05/16/lifecycle-hooks-in-vue-3/</link>
					<comments>https://programeasily.com/2021/05/16/lifecycle-hooks-in-vue-3/#respond</comments>
		
		<dc:creator><![CDATA[Admin]]></dc:creator>
		<pubDate>Sun, 16 May 2021 17:56:43 +0000</pubDate>
				<category><![CDATA[Vuejs]]></category>
		<category><![CDATA[vue]]></category>
		<category><![CDATA[vue3]]></category>
		<guid isPermaLink="false">http://programeasily.com/?p=106</guid>

					<description><![CDATA[<p>In the modern programming world, creating web pages using HTML directly is not very effective. Rather people prefer Components to create HTML web pages. Because the components ease the development, performance and readability. We can divide the web pages into pieces of components. Each Component is responsible for its own business. While we create components, we will go step by step procedure to fulfill its requirements. In Vue.js we can derive this as follows, Data observation template compilation mount the...</p>
<p class="read-more"><a class="btn btn-default" href="https://programeasily.com/2021/05/16/lifecycle-hooks-in-vue-3/"> Read More<span class="screen-reader-text">  Read More</span></a></p>
<p>The post <a rel="nofollow" href="https://programeasily.com/2021/05/16/lifecycle-hooks-in-vue-3/">Lifecycle hooks in Vue 3</a> appeared first on <a rel="nofollow" href="https://programeasily.com">Program Easily</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In the modern programming world, creating web pages using HTML directly is not very effective. Rather people prefer Components to create HTML web pages. Because the components ease the development, performance and readability. We can divide the web pages into pieces of components. Each Component is responsible for its own business.</p>
<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-270" src="https://i0.wp.com/programeasily.com/wp-content/uploads/2021/05/Lifecycle-hooks-in-Vue-3.jpg?resize=640%2C426&#038;ssl=1" alt="Lifecycle hooks in Vue 3" width="640" height="426" srcset="https://i0.wp.com/programeasily.com/wp-content/uploads/2021/05/Lifecycle-hooks-in-Vue-3.jpg?w=1280&amp;ssl=1 1280w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/05/Lifecycle-hooks-in-Vue-3.jpg?resize=300%2C200&amp;ssl=1 300w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/05/Lifecycle-hooks-in-Vue-3.jpg?resize=1024%2C682&amp;ssl=1 1024w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/05/Lifecycle-hooks-in-Vue-3.jpg?resize=768%2C511&amp;ssl=1 768w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/05/Lifecycle-hooks-in-Vue-3.jpg?resize=406%2C270&amp;ssl=1 406w" sizes="auto, (max-width: 640px) 100vw, 640px" data-recalc-dims="1" /></p>
<p>While we create components, we will go step by step procedure to fulfill its requirements. In Vue.js we can derive this as follows,</p>
<ol>
<li>Data observation</li>
<li>template compilation</li>
<li>mount the component instance to DOM</li>
<li>update the DOM based on data</li>
</ol>
<p>Between the steps, Vue.js provides a predefined function called <strong>Life Cycle Hooks</strong>. We can add our own logics by calling these life cycle hooks in between the component creations. It will be very helpful to know about <a href="https://programeasily.com/2020/12/22/components-in-vue3/" target="_blank" rel="noopener">Components in Vue3</a> before moving to this session. Let’s take the deep dive!</p>
<h2>Lifecycle hooks in Vue 3</h2>
<p>For Example, As per the component creation flow, the created hook will be called after the component instance is created.</p>
<pre><code class="language-javascript">Vue.createApp({
  data() {
    return { state: "hello to lifecycle hooks" }
  },
  created() {
    // `this` points to the vm instance
    console.log(this.state) // =&gt; hello to lifecycle hooks
  }
})</code></pre>
<p>As shown above, we can use other hooks which are used to be called at different stages of component creation.</p>
<h2>Options API vs Composition API</h2>
<p>Above all, we can access lifecycle hooks in both options API and composition API. We have to invoke life cycle methods inside the setup function in the Composition API. Option API is available in both Vue.js 2 and 3 whereas composition API is available from Vue.js 3.</p>
<table style="height: 331px;" width="628">
<thead>
<tr>
<th>Options API</th>
<th>Composition API</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>beforeCreate</code></td>
<td>Not needed* (directly write in setup)</td>
</tr>
<tr>
<td><code>created</code></td>
<td>Not needed*(directly write in setup)</td>
</tr>
<tr>
<td><code>beforeMount</code></td>
<td><code>onBeforeMount</code></td>
</tr>
<tr>
<td><code>mounted</code></td>
<td><code>onMounted</code></td>
</tr>
<tr>
<td><code>beforeUpdate</code></td>
<td><code>onBeforeUpdate</code></td>
</tr>
<tr>
<td><code>updated</code></td>
<td><code>onUpdated</code></td>
</tr>
<tr>
<td><code>beforeUnmount</code></td>
<td><code>onBeforeUnmount</code></td>
</tr>
<tr>
<td><code>unmounted</code></td>
<td><code>onUnmounted</code></td>
</tr>
<tr>
<td><code>errorCaptured</code></td>
<td><code>onErrorCaptured</code></td>
</tr>
<tr>
<td><code>renderTracked</code></td>
<td><code>onRenderTracked</code></td>
</tr>
<tr>
<td><code>renderTriggered</code></td>
<td><code>onRenderTriggered</code></td>
</tr>
</tbody>
</table>
<p>Most importantly, <code>beforeCreate</code> and <code>created</code> are not available in composition API. However, we can write it&#8217;s logic directly in the setup function since setup is invoked around the created hook.</p>
<h4>Note</h4>
<p>In Optional API, all lifecycle hooks have <em><strong>this</strong></em> context bound to the instance. So we should not go for arrow functions (e.g. <code>created: () =&gt; this.createdCallBack()</code>) since arrow functions bind the parent context to <strong><em>this</em></strong>.</p>
<h2>Lifecycle hooks &#8211; Options API</h2>
<ul>
<li>beforeCreate &#8211; called after the component instance has been <strong>initialized</strong> but before data observation.</li>
<li>created &#8211; called after the component instance has been created. Since instance is created we can set up data observation, computed properties, methods, watch/event callbacks. But we can not do DOM operation since the component is not mounted. The $el property is also not available yet.</li>
<li>beforeMount &#8211; called just before the component mounting process.</li>
<li>mounted &#8211; This is an important hook after created hook in the options API. mounted called after the component instance has been mounted. If the root component instance is mounted, then vm.$el will be there in the DOM. But it does not guarantee that all child components have also been mounted.</li>
<li>beforeUpdate &#8211; called at run time when data changes before the DOM is updated. It is a good place to remove manually added event listeners.</li>
<li>updated &#8211; called at runtime after the data changes and DOM patched.</li>
<li>beforeUnMount &#8211; called before a component instance is unmounted.</li>
<li>unmounted &#8211; called after a component instance has been unmounted.</li>
<li>errorCaptured &#8211; called when an error occurs from any child component.</li>
<li>renderTracked &#8211; called when virtual DOM rerender tracked.</li>
<li>renderTriggered &#8211; called when virtual DOM rerender triggered.</li>
</ul>
<h2>Lifecycle hooks Vue 3 Example</h2>
<p>Life cycle hooks provide the ways to add their logic at specific stages while creating the components. Moreover in Vue.js 3, they are tree-shakable modules. You can import and use them in your composable logics.</p>
<pre><code class="language-javascript">import { onMounted } from "vue";</code></pre>
<p>As shown above, we can get the lifecycle hooks  and use them in our logics at different stages. The full example for all lifecycle hooks shown below,</p>
<pre><code class="language-javascript">&lt;template&gt;
  &lt;div&gt;
    &lt;button v-on:click="addToCart"&gt;Add to cart&lt;/button&gt;
    &lt;p&gt;Cart{{ state }}&lt;/p&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
import {
  onBeforeMount,
  onMounted,
  onBeforeUpdate,
  onUpdated,
  onBeforeUnmount,
  onUnmounted,
  onErrorCaptured,
  onRenderTracked,
  onRenderTriggered,
  ref,
} from "vue";

export default {
  setup() {
    onBeforeMount(() =&gt; {
      console.log("Component is onBeforeMount!");
    });
    onMounted(() =&gt; {
      console.log("Component is mounted!");
    });
    onBeforeUpdate(() =&gt; {
      console.log("Component is onBeforeUpdate!");
    });
    onUpdated(() =&gt; {
      console.log("Component is Updated!");
    });
    onBeforeUnmount(() =&gt; {
      console.log("Component is onBeforeUnmount!");
    });
    onUnmounted(() =&gt; {
      console.log("Component is un mounted!");
    });
    onErrorCaptured(() =&gt; {});
    onRenderTracked(({ key, target, type }) =&gt; {
      console.log("onRenderTriggered!")
      console.log({ key, target, type });
      /* This will be logged when component is rendered for the first time:
    {
      key: "cart",
      target: {
        cart: 0
      },
      type: "get"
    }
    */
    });
    onRenderTriggered(({ key, target, type }) =&gt; {
      console.log("onRenderTriggered!")
      console.log({ key, target, type });
      /* This will be logged when component is rendered for the first time:
    {
      key: "cart",
      target: {
        cart: 0
      },
      type: "get"
    }
    */
    });

    let state = ref(0);
    const addToCart = () =&gt; {
      state.value += 1;
    };
    return {
      state,
      addToCart,
    };
  },
};
&lt;/script&gt;

&lt;style scoped&gt;&lt;/style&gt;</code></pre>
<p>&nbsp;</p>
<h4><strong>GitHub Link :</strong></h4>
<ul>
<li><a href="https://github.com/programeasily/vue-3-basics/blob/main/src/components/HooksExampleComponent.vue">https://github.com/programeasily/vue-3-basics/blob/main/src/components/HooksExampleComponent.vue</a></li>
</ul>
<p>&nbsp;</p>
<h4>References :</h4>
<ol>
<li><a href="https://v3.vuejs.org/guide/instance.html#lifecycle-hooks">https://v3.vuejs.org/guide/instance.html#lifecycle-hooks</a></li>
<li><a href="https://v3.vuejs.org/api/options-lifecycle-hooks.html#lifecycle-hooks">https://v3.vuejs.org/api/options-lifecycle-hooks.html#lifecycle-hooks</a></li>
<li><a href="https://v3.vuejs.org/guide/composition-api-lifecycle-hooks.html">https://v3.vuejs.org/guide/composition-api-lifecycle-hooks.html</a></li>
</ol>
<h2>Summary</h2>
<p><b>In conclusion</b>,</p>
<ul>
<li>Firstly vue.js provides predefined function called Life Cycle Hooks.</li>
<li>Secondly we can access lifecycle hooks in both options API and composition API.</li>
<li>Life cycle hooks provide the way to add their logics at specific stages while creating the components.</li>
</ul>
<p>The post <a rel="nofollow" href="https://programeasily.com/2021/05/16/lifecycle-hooks-in-vue-3/">Lifecycle hooks in Vue 3</a> appeared first on <a rel="nofollow" href="https://programeasily.com">Program Easily</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://programeasily.com/2021/05/16/lifecycle-hooks-in-vue-3/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">106</post-id>	</item>
		<item>
		<title>Provide And Inject in Vue.js</title>
		<link>https://programeasily.com/2021/04/17/provide-and-inject-in-vue-js/</link>
					<comments>https://programeasily.com/2021/04/17/provide-and-inject-in-vue-js/#respond</comments>
		
		<dc:creator><![CDATA[Admin]]></dc:creator>
		<pubDate>Sat, 17 Apr 2021 14:17:55 +0000</pubDate>
				<category><![CDATA[Vuejs]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[vuejs]]></category>
		<category><![CDATA[vuejs3]]></category>
		<guid isPermaLink="false">http://programeasily.com/?p=37</guid>

					<description><![CDATA[<p>Provide and Inject are the advanced concepts of Vue.js Components module. It&#8217;s not mostly needed for small structured components. But imagine if the structures are deeply nested. Then we are in need to pass data from parent to innermost child component. It&#8217;s a completely difficult situation right now. To solve this problem, Vue.js introduced Provide and Inject concepts. Here the parent component provides the dependency to all its children irrespective of how long the component hierarchy is. As the name...</p>
<p class="read-more"><a class="btn btn-default" href="https://programeasily.com/2021/04/17/provide-and-inject-in-vue-js/"> Read More<span class="screen-reader-text">  Read More</span></a></p>
<p>The post <a rel="nofollow" href="https://programeasily.com/2021/04/17/provide-and-inject-in-vue-js/">Provide And Inject in Vue.js</a> appeared first on <a rel="nofollow" href="https://programeasily.com">Program Easily</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><em>Provide and Inject</em> are the advanced concepts of Vue.js Components module. It&#8217;s not mostly needed for small structured components. But imagine if the structures are deeply nested. Then we are in need to pass data from parent to innermost child component. It&#8217;s a completely difficult situation right now.</p>
<p>To solve this problem, Vue.js introduced <em>Provide and Inject</em> concepts. Here the parent component provides the dependency to all its children irrespective of how long the component hierarchy is. As the name suggests, the parent component has a <em>provide</em> option and the child component has an <em>inject</em> option. <strong>The provide option will <em>provide</em> the data and <em>inject</em> will acquire this data.</strong></p>
<p>Let&#8217;s take a deep dive into this with an example. Read <a href="https://programeasily.com/2020/12/22/components-in-vue3/" target="_blank" rel="noopener">Components in Vue3</a> and <a href="https://programeasily.com/2020/12/31/single-file-components-vue-3/" target="_blank" rel="noopener">Single File Components Vue 3</a> if you are new to Vue.js components.</p>
<h2><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-241" src="https://i0.wp.com/programeasily.com/wp-content/uploads/2021/04/provideandinjectinvue.js.jpg?resize=640%2C427&#038;ssl=1" alt="provideandinjectinvue.js" width="640" height="427" srcset="https://i0.wp.com/programeasily.com/wp-content/uploads/2021/04/provideandinjectinvue.js.jpg?w=1920&amp;ssl=1 1920w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/04/provideandinjectinvue.js.jpg?resize=300%2C200&amp;ssl=1 300w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/04/provideandinjectinvue.js.jpg?resize=1024%2C683&amp;ssl=1 1024w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/04/provideandinjectinvue.js.jpg?resize=768%2C512&amp;ssl=1 768w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/04/provideandinjectinvue.js.jpg?resize=1536%2C1024&amp;ssl=1 1536w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/04/provideandinjectinvue.js.jpg?resize=405%2C270&amp;ssl=1 405w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/04/provideandinjectinvue.js.jpg?w=1280&amp;ssl=1 1280w" sizes="auto, (max-width: 640px) 100vw, 640px" data-recalc-dims="1" /></h2>
<pre><code class="language-markup">Root
└─ Page (&lt;- Use Provide Here -&gt;)
   ├─ App Bar
   └─ Layout
      ├─ Drawer Menu
      └─ Main Floor
         └─ Header Room (&lt;- Use Inject Here -&gt;)
         └─ Content Room
   └─ Footer</code></pre>
<p>Let me take the above example, where we want Page component data in Header room component. We can pass as prop data from <strong>Page -&gt; Layout -&gt; Main Floor -&gt; Header Room</strong>  components one by one. Alternatively we can use <em>provide</em>/<em>inject</em> here.</p>
<h3>Use Provide</h3>
<p>Firstly, our goal is to pass Page Component data to it&#8217;s inner child Header Room Component without passing as prop data.  So we are using <em>Provide</em> in Page.vue.</p>
<pre><code class="language-javascript">Page.vue

&lt;template&gt;
  &lt;div /&gt;
  &lt;!-- &lt;AppBar /&gt; 
  // Here we supposed to pass pageProperties
  // to Layout and Layout -&gt; Main Floor -&gt; Header Room
  // But with the help of provide/inject we can directly
  // use this in Header Room component --&gt;
  &lt;Layout /&gt;
&lt;/template&gt;

&lt;script&gt;
import Layout from "./Layout";
export default {
  components: {
    Layout,
  },
  provide: {
    pageProperties: {
      pageName: "Provide/Inject",
      pageVersion: "1.0.0",
      pageUser: "admin",
    },
  },
};
&lt;/script&gt;</code></pre>
<h3>Use Inject</h3>
<p>Secondly, we will be using <em>inject</em> in HeaderRoom.vue Component to get the data given in Page.vue Component with <em>provide</em> option.</p>
<pre><code class="language-javascript">HeaderRoom.vue

&lt;template&gt;
  &lt;div&gt;Page Name : {{ pageProperties.pageName }}&lt;/div&gt;
  &lt;div&gt;Page Name : {{ pageProperties.pageVersion }}&lt;/div&gt;
  &lt;div&gt;Page Name : {{ pageProperties.pageUser }}&lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
export default {
  inject: ["pageProperties"],
};
&lt;/script&gt;</code></pre>
<h4>The full working example</h4>
<p><iframe style="width: 100%; height: 500px; border: 0; border-radius: 4px; overflow: hidden;" title="vue-3-basics-program-easily" src="https://codesandbox.io/embed/github/programeasily/vue-3-basics/tree/main/?fontsize=14&amp;hidenavigation=1&amp;view=split&amp;initialpath=provideandinjectdemo&amp;module=%2Fsrc%2Fcomponents%2Fprovideinject%2FPage.vue&amp;theme=dark" sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"><span data-mce-type="bookmark" style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" class="mce_SELRES_start">﻿</span></iframe></p>
<h3>Note :</h3>
<p>Some points to be noted here,</p>
<ol>
<li><span style="font-weight: 400;">Parent component wouldn&#8217;t know which child is going to use the provided data.</span></li>
<li><span style="font-weight: 400;">Likewise the child component wouldn&#8217;t be aware where the injected data coming from.</span></li>
</ol>
<h2>Provide And Inject in Vue.js with Composition API</h2>
<p>In addition, we can use <em>provide</em> and <em>inject</em> in the composition API also. We have to call both methods inside the <a href="https://programeasily.com/2021/01/04/setup-function-in-composition-api-vue-3/" target="_blank" rel="noopener">setup function.</a></p>
<h3>Provide in setup</h3>
<p>We have to import <em>provide</em> function from vue module. The <em>provide</em> function has two parameters,</p>
<ol>
<li>The Property Name (type should be string)</li>
<li>The Property Value  (type can be anything)</li>
</ol>
<p>we are updating  Page.vue component as follows,</p>
<pre><code class="language-javascript">Page.vue

&lt;template&gt;
  &lt;div /&gt;
  &lt;!-- &lt;AppBar /&gt; 
  // Here we supposed to pass pageProperties
  // to Layout and Layout -&gt; Main Floor -&gt; Header Room
  // But with the help of provide/inject we can directly
  // use this in Header Room component --&gt;
  &lt;Layout /&gt;
&lt;/template&gt;

&lt;script&gt;
import { provide } from "vue";
import Layout from "../provideinject/Layout";
export default {
  components: {
    Layout,
  },
  setup() {
    provide("pageProperties", {
      pageName: "Provide/Inject",
      pageVersion: "1.0.0",
      pageUser: "admin",
    });
  },
};
&lt;/script&gt;</code></pre>
<h3>Inject in setup</h3>
<p><span style="font-weight: 400;">We have to import the <em>inject</em> function from the vue module</span>. The <em>inject</em> function has two parameters,</p>
<ol>
<li>The property Name</li>
<li>Default value (optional)</li>
</ol>
<p>we are updating  HeaderRoom.vue component as follows,</p>
<pre><code class="language-javascript">HeaderRomm.vue

&lt;template&gt;
  &lt;div&gt;Page Name : {{ pageProperties.pageName }}&lt;/div&gt;
  &lt;div&gt;Page Name : {{ pageProperties.pageVersion }}&lt;/div&gt;
  &lt;div&gt;Page Name : {{ pageProperties.pageUser }}&lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
import { inject } from "vue";
export default {
  setup() {
    let pageProperties = inject("pageProperties");
    return {
      pageProperties,
    };
  },
};
&lt;/script&gt;</code></pre>
<h4>The full working example</h4>
<p><iframe style="width: 100%; height: 500px; border: 0; border-radius: 4px; overflow: hidden;" title="vue-3-basics-program-easily" src="https://codesandbox.io/embed/github/programeasily/vue-3-basics/tree/main/?fontsize=14&amp;hidenavigation=1&amp;view=split&amp;initialpath=provideandinjectsetupdemo&amp;module=%2Fsrc%2Fcomponents%2Fprovideinject-setup%2FPage.vue&amp;theme=dark" sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"><span data-mce-type="bookmark" style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" class="mce_SELRES_start">﻿</span></iframe></p>
<h2>Provide And Inject in Vue.js with Reactivity</h2>
<p>In the above example, pageProperties will not be reactive by default. Moreover, They are not reactive by nature. <strong>We have to use <em>ref/reactive</em> with <em>provide</em> to make it reactive.</strong></p>
<p>Note that, In the below example we are using <em>reactive</em> with <em>provide</em> to make pageProperties reactive. Here updateVersion method is provided to all it&#8217;s children with pageProperties.</p>
<pre><code class="language-javascript">Page.vue

&lt;template&gt;
  &lt;div /&gt;
  &lt;!-- &lt;AppBar /&gt; 
  // Here we supposed to pass pageProperties
  // to Layout and Layout -&gt; Main Floor -&gt; Header Room
  // But with the help of provide/inject we can directly
  // use this in Header Room component --&gt;
  &lt;Layout /&gt;
&lt;/template&gt;

&lt;script&gt;
import { provide, reactive } from "vue";
import Layout from "./Layout";
export default {
  components: {
    Layout,
  },
  setup() {
    let pageProperties = reactive({
      pageName: "Provide/Inject",
      pageVersion: "1.0.0",
      pageUser: "admin",
    });
    provide("pageProperties", pageProperties);
    provide("updateVersion", () =&gt; {
      pageProperties.pageVersion = "2.0.0";
    });
    return {
      pageProperties,
    };
  },
};
&lt;/script&gt;</code></pre>
<p>After that, we are going to update the version from HeaderRoom Component with the help of <em>inject</em> directly.</p>
<pre><code class="language-javascript">HeaderRoom.vue

&lt;template&gt;
  &lt;div&gt;
    &lt;button @click="updateVersion"&gt;Update Parent Version&lt;/button&gt;
  &lt;/div&gt;
  &lt;div&gt;Page Name : {{ pageProperties.pageName }}&lt;/div&gt;
  &lt;div&gt;Page Name : {{ pageProperties.pageVersion }}&lt;/div&gt;
  &lt;div&gt;Page Name : {{ pageProperties.pageUser }}&lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
import { inject } from "vue";
export default {
  setup() {
    let pageProperties = inject("pageProperties");
    let updateVersion = inject("updateVersion");
    return {
      pageProperties,
      updateVersion,
    };
  },
};
&lt;/script&gt;</code></pre>
<p>So we can update parent component data(pageProperties version) from the child component using <em>provide</em> and <em>inject</em> concepts in Vue.js effectively.</p>
<h4>The full working example</h4>
<p><iframe style="width: 100%; height: 500px; border: 0; border-radius: 4px; overflow: hidden;" title="vue-3-basics-program-easily" src="https://codesandbox.io/embed/github/programeasily/vue-3-basics/tree/main/?fontsize=14&amp;hidenavigation=1&amp;view=split&amp;initialpath=provideandinjectreactivedemo&amp;module=%2Fsrc%2Fcomponents%2Fprovideinject-reactive%2FPage.vue&amp;theme=dark" sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"><span data-mce-type="bookmark" style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" class="mce_SELRES_start">﻿</span></iframe></p>
<h2>Global Provider &#8211; Provide Application API</h2>
<p>However, we can use <em>provide</em> as a global provider to all components. <strong>The provided data would be injected to all it&#8217;s components within the application.</strong> It&#8217;s an alternative way for <a href="https://v3.vuejs.org/api/application-config.html#globalproperties" target="_blank" rel="noopener">global properties</a> in Vue.js.</p>
<p>Let me show you the example below,</p>
<p>index.js</p>
<pre><code class="language-javascript">const app = Vue.createApp({});
// Global Provider
app.provide("appProperties", {
  user: "admin",
  appVersion: "1.0.0"
});
// Page Component where contains content component
app.component("Page", {
  template: `&lt;Content /&gt;`
});
// Content component where inject used to get
// global properties
app.component("Content", {
  inject: ["appProperties"],
  template: `
    &lt;div&gt;User Name : {{ appProperties.user }}&lt;/div&gt;
    &lt;div&gt;Version : {{ appProperties.appVersion }}&lt;/div&gt;
  `
});</code></pre>
<p>index.html</p>
<pre><code class="language-markup">&lt;div id="app"&gt;
      &lt;Page /&gt;
&lt;/div&gt;</code></pre>
<p>Here the <code>appProperties</code> is provided to all components within the application. We got the data in the <strong>Content</strong> component using <em>inject</em>.</p>
<h4>The full working example</h4>
<p><iframe style="width: 100%; height: 500px; border: 0; border-radius: 4px; overflow: hidden;" title="global-provider-provide-inject-vuejs" src="https://codesandbox.io/embed/github/programeasily/global-provider-example-vue/tree/main/?fontsize=14&amp;hidenavigation=1&amp;theme=dark&amp;view=split" sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"><span data-mce-type="bookmark" style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" class="mce_SELRES_start">﻿</span></iframe></p>
<h2>Conclusion</h2>
<ul>
<li>In conclusion, <strong><em>Provide</em> and <em>inject</em> makes ease of data communication between parent and it&#8217;s child components.</strong></li>
<li><em>Provide</em> and <em>Inject</em> are not reactive by nature. But we can make it reactive with the help of <em>reactive/ref</em>.</li>
<li>We can use <em>provide</em> as global provider instead of global properties in Vue.js</li>
</ul>
<p>The post <a rel="nofollow" href="https://programeasily.com/2021/04/17/provide-and-inject-in-vue-js/">Provide And Inject in Vue.js</a> appeared first on <a rel="nofollow" href="https://programeasily.com">Program Easily</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://programeasily.com/2021/04/17/provide-and-inject-in-vue-js/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">37</post-id>	</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/

Page Caching using disk: enhanced 
Minified using disk
Database Caching using disk (Request-wide modification query)

Served from: programeasily.com @ 2025-06-20 08:01:28 by W3 Total Cache
-->