<?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>javascript Archives - Program Easily</title>
	<atom:link href="https://programeasily.com/tag/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>https://programeasily.com/tag/javascript/</link>
	<description>Program Easily helps people to learn about software programs in a easy manner.</description>
	<lastBuildDate>Thu, 15 Dec 2022 03:57:31 +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>javascript Archives - Program Easily</title>
	<link>https://programeasily.com/tag/javascript/</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">187075990</site>	<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 fetchpriority="high" 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="(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>
		<item>
		<title>getCurrentInstance in Vue 3</title>
		<link>https://programeasily.com/2021/02/24/getcurrentinstance-in-vue-3/</link>
					<comments>https://programeasily.com/2021/02/24/getcurrentinstance-in-vue-3/#respond</comments>
		
		<dc:creator><![CDATA[Admin]]></dc:creator>
		<pubDate>Wed, 24 Feb 2021 16:35:10 +0000</pubDate>
				<category><![CDATA[Vuejs]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[vue3]]></category>
		<category><![CDATA[vuejs]]></category>
		<guid isPermaLink="false">http://programeasily.com/?p=35</guid>

					<description><![CDATA[<p>Being developers we all used to work with this reference in programming. In Vue.js 2, this instance is available in option objects. We can access this inside the method, computed, watch and data. But when it comes to Vue.js 3 it is all about composition API. In the composition API we will be using setup to compose or organize our component business logics. Here, this will not be available inside the setup hook. Because the component is not created yet....</p>
<p class="read-more"><a class="btn btn-default" href="https://programeasily.com/2021/02/24/getcurrentinstance-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/02/24/getcurrentinstance-in-vue-3/">getCurrentInstance in Vue 3</a> appeared first on <a rel="nofollow" href="https://programeasily.com">Program Easily</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Being developers we all used to work with <strong>this</strong> reference in programming. In Vue.js 2, <em>this</em> instance is available in option objects. We can access <em>this</em> inside the method, computed, watch and data. But when it comes to Vue.js 3 it is all about composition API. In the composition API we will be using setup to compose or organize our component business logics. Here, <em>this</em> will not be available inside the setup hook. Because the component is not created yet. To know more about setup function, you can refer <a href="https://programeasily.com/2021/01/04/setup-function-in-composition-api-vue-3/" target="_blank" rel="noopener">Setup function in Composition API – Vue 3</a></p>
<p>So Vue.js 3 <span style="font-weight: 400;">provides the getCurrentInstance</span> function for us. Using <span style="font-weight: 400;">getCurrentInstance</span>, we can access component instance inside the setup hook. It will be available inside <a href="https://v3.vuejs.org/api/composition-api.html#lifecycle-hooks" target="_blank" rel="noopener">Lifecycle Hooks</a> also. Let&#8217;s take a deep dive!.</p>
<p><img decoding="async" class="aligncenter size-full wp-image-210" src="https://i0.wp.com/programeasily.com/wp-content/uploads/2021/02/getCurrentInstance-in-Vue-3.jpg?resize=640%2C427&#038;ssl=1" alt="getCurrentInstance in Vue 3" width="640" height="427" srcset="https://i0.wp.com/programeasily.com/wp-content/uploads/2021/02/getCurrentInstance-in-Vue-3.jpg?w=1920&amp;ssl=1 1920w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/02/getCurrentInstance-in-Vue-3.jpg?resize=300%2C200&amp;ssl=1 300w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/02/getCurrentInstance-in-Vue-3.jpg?resize=1024%2C683&amp;ssl=1 1024w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/02/getCurrentInstance-in-Vue-3.jpg?resize=768%2C512&amp;ssl=1 768w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/02/getCurrentInstance-in-Vue-3.jpg?resize=1536%2C1024&amp;ssl=1 1536w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/02/getCurrentInstance-in-Vue-3.jpg?resize=405%2C270&amp;ssl=1 405w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/02/getCurrentInstance-in-Vue-3.jpg?w=1280&amp;ssl=1 1280w" sizes="(max-width: 640px) 100vw, 640px" data-recalc-dims="1" /></p>
<h2>getCurrentInstance in Vue 3</h2>
<p>In short, we can use getCurrentInstance to get component instances. This is the replacement of <em>this</em> in Vue.js 2. It will be very useful for custom Vue.js library authors and advanced developers for construction of complex components. Let me explain it with an example below.</p>
<h3>Setup function Example</h3>
<pre><code class="language-javascript">import { getCurrentInstance } from "vue";
export default {
  setup() {
    // accessible inside setup function
    const instance = getCurrentInstance();
    console.log(instance);
  },
};</code></pre>
<p>Note that, getCurrentInstance won&#8217;t work outside of setup function and lifecycle hooks. If you want to access it call getCurrentInstance in the setup function and use the reference as follows,</p>
<pre><code class="language-javascript">import { getCurrentInstance } from "vue";
export default {
  setup() {
    // accessible inside setup function
    const instance = getCurrentInstance();
    
    const eventCallback = () =&gt; {
        getCurrentInstance(); // won't work here
        console.log(instance); // But you can use instance reference here
    }
    return {
        eventCallback
    }
  },
};</code></pre>
<h3>Lifecycle hook example</h3>
<pre><code class="language-javascript">import { getCurrentInstance, onMounted, onUpdated, onUnmounted } from "vue";
export default {
  setup() {
    // Accessible in All lifecycle methods
    onMounted(() =&gt; {
      let instance = getCurrentInstance();
      console.log(instance);
      console.log("mounted!");
    });
    onUpdated(() =&gt; {
      let instance = getCurrentInstance();
      console.log(instance);
      console.log("updated!");
    });
    onUnmounted(() =&gt; {
      let instance = getCurrentInstance();
      console.log(instance);
      console.log("unmounted!");
    });
    return {};
  },
};</code></pre>
<p>Note that, it will be accessible on composable function, when we call from setup function.</p>
<h2>Real Time Example &#8211; getCurrentInstance Vue 3</h2>
<p>Meanwhile, you may wonder why I need getCurrentInstance?. We can create a component using props, data and other Utilities. But when component logic increases or for a library creator, they need one component instance in another place. This is the case where we can use getCurrentInstance. Using getCurrentInsance we can access below things,</p>
<ul>
<li>appContext.config.globalProperties &#8211; get the global properties</li>
<li>proxy &#8211; get the reactive proxy object of the component. By using this, we can change the reactive data</li>
<li>props &#8211; get all the props of component</li>
<li>emit &#8211; can be used to dispatch the events</li>
<li>vnode.el &#8211; the DOM element</li>
<li>refs &#8211; if ref is used in the child component, we can get all instance of child component using refs</li>
<li>and much more!. just console.log it, and we can see the same.</li>
</ul>
<p>So in the below example, we are storing a proxy object reference with the help of getCurrentInstance. By using this object we can change respected component reactive data and invoke it&#8217;s methods.</p>
<p>&nbsp;</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;view=split&amp;initialpath=getcurrentinstancedemo&amp;module=%2Fsrc%2Fpage%2FGetCurrentInstanceDemo.vue&amp;theme=light" 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>
<p>Firstly in the Button.vue file we are storing a proxy object with the help of getCurrentInstance as follows.</p>
<pre><code class="language-javascript">// getCurrentInstance accessible on a composable function
// But it should be called inside setup function
const useBase = function (props) {
  onMounted(() =&gt; {
    let instance = getCurrentInstance();
    // Component instance stored in a global store.
    store.setInstance(props.id, instance.proxy);
  });
};</code></pre>
<p>Secondly we are using store.js to store the getCurrentInstance proxy object as follows,</p>
<pre><code class="language-javascript">const store = {}
/**
 * A Global Store for component instances
 * Note that id should be unique
 */
export default {
    setInstance(id,proxy){
        store[id] = proxy;
    },
    getInstance(id){
        return store[id];
    }
}</code></pre>
<p>Further, In the GetCurrentInstanceDemo.vue file, we get the stored proxy object of the button component using unique id. By using this reference, we can invoke it&#8217;s methods as follows,</p>
<pre><code class="language-javascript">const onMouseover = () =&gt; {
     // Here we can access Button component instance
    // And invoke it's methods using proxy object
     store.getInstance("btn").hide();
}
const onMouseleave = () =&gt; {
    store.getInstance("btn").show();
}</code></pre>
<p>This is one of the use cases of getCurrentInstance. Likewise you can use it instead of <strong>this </strong>in Vue.js 2 based on your use cases.</p>
<h2>Conclusion</h2>
<p>In conclusion,<b> </b>getCurrentInstance is the special feature of Vue.js 3. We can use it instead of <strong>this</strong> in Composition API. By using it we can get a lot of utilities like emit, all props, data, proxy object, el DOM element.</p>
<p>The post <a rel="nofollow" href="https://programeasily.com/2021/02/24/getcurrentinstance-in-vue-3/">getCurrentInstance 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/02/24/getcurrentinstance-in-vue-3/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">35</post-id>	</item>
		<item>
		<title>Computed in Vue 3</title>
		<link>https://programeasily.com/2021/01/30/computed-in-vue-3/</link>
					<comments>https://programeasily.com/2021/01/30/computed-in-vue-3/#respond</comments>
		
		<dc:creator><![CDATA[Admin]]></dc:creator>
		<pubDate>Sat, 30 Jan 2021 16:55:45 +0000</pubDate>
				<category><![CDATA[Vuejs]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[vue3]]></category>
		<category><![CDATA[vuejs]]></category>
		<guid isPermaLink="false">http://programeasily.com/?p=104</guid>

					<description><![CDATA[<p>Vue.js has six options which are data, props, computed, methods, watch and emits. Among them, we are going to discuss about computed in vue 3 options. We can use this option while creating the components. It will ease the complex component creations and logics. We can write or compose a component logics using computed. In Vue.js 2, we will use computed as a property of SFC&#8217;s. But Computed in Vue 3 moved to separate module. So we have to import...</p>
<p class="read-more"><a class="btn btn-default" href="https://programeasily.com/2021/01/30/computed-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/01/30/computed-in-vue-3/">Computed in Vue 3</a> appeared first on <a rel="nofollow" href="https://programeasily.com">Program Easily</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Vue.js has six options which are data, props, computed, methods, watch and emits. Among them, we are going to discuss about computed in vue 3 options. We can use this option while creating the components. It will ease the complex component creations and logics. We can write or compose a component logics using computed.</p>
<p>In Vue.js 2, we will use computed as a property of SFC&#8217;s. But Computed in Vue 3 moved to separate module. So we have to import from vue. Let&#8217;s take a deep dive!.</p>
<p>Note that, we are using Single file Components SFC&#8217;s in examples. So you can refer more about SFC&#8217;s from <a href="https://programeasily.com/2020/12/31/single-file-components-vue-3/" target="_blank" rel="noopener">Single File Components Vue 3</a></p>
<p><img decoding="async" class="aligncenter size-full wp-image-190" src="https://i0.wp.com/programeasily.com/wp-content/uploads/2021/01/computed-in-vue-3.jpg?resize=640%2C427&#038;ssl=1" alt="Computed in Vue 3" width="640" height="427" srcset="https://i0.wp.com/programeasily.com/wp-content/uploads/2021/01/computed-in-vue-3.jpg?w=1920&amp;ssl=1 1920w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/01/computed-in-vue-3.jpg?resize=300%2C200&amp;ssl=1 300w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/01/computed-in-vue-3.jpg?resize=1024%2C683&amp;ssl=1 1024w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/01/computed-in-vue-3.jpg?resize=768%2C512&amp;ssl=1 768w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/01/computed-in-vue-3.jpg?resize=1536%2C1024&amp;ssl=1 1536w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/01/computed-in-vue-3.jpg?resize=405%2C270&amp;ssl=1 405w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/01/computed-in-vue-3.jpg?w=1280&amp;ssl=1 1280w" sizes="(max-width: 640px) 100vw, 640px" data-recalc-dims="1" /></p>
<h2 style="text-align: left;">Computed in Vue 3</h2>
<p>There are two basic reasons to use computed property.</p>
<ol>
<li>Behavior Dependency on reactive variables.</li>
<li>To move complex template logics on reactive variables.</li>
</ol>
<h3>Behavior Dependency</h3>
<p>Every component has unique core logics, in such a way that it will fulfill it&#8217;s requirements. While organizing the component logic, sometimes we need one behavior that depends on the other behaviors. We can handle this situation using computed properties. Computed has two properties namely get and set.</p>
<h3>get function</h3>
<p>The computed method takes a getter function, and it will return the reactive immutable ref object. There are two syntax to create get function,</p>
<p>Note that, here the function is given as an argument of computed method directly.</p>
<pre><code class="language-javascript">const fullName = computed(() =&gt; {
      return props.firstName + " " + props.lastName;
 });</code></pre>
<p>Alternatively, we can assign the function on get property as follows,</p>
<pre><code class="language-javascript">const fullName = computed({
      get: () =&gt; {
        return props.firstName + " " + props.lastName;
      },
 });
</code></pre>
<p>Now we are going to see the full example for computed getter function. The important point here is that the fullName depends on first name and last name. The fullName takes a getter function and return reactive ref object. We will return this fullName object from the setup hook.</p>
<h4>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/vue-3-basics-program-easily-d5r06?fontsize=14&amp;view=split&amp;hidenavigation=1&amp;initialpath=computedgetdemo&amp;module=%2Fsrc%2Fcomponents%2FComputedGetSample.vue&amp;theme=light" sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"></iframe></p>
<h3>set function</h3>
<p>We have one more set function to create a writable ref object. We won&#8217;t use setter function mostly in computed method. It has only one syntax as follows,</p>
<pre><code class="language-javascript">const counterResult = computed({
      set: (val) =&gt; {
        counter.value = counter.value + val
      },
 });
// To increment
counterResult = 1 // It will increment by one</code></pre>
<p>Now we are going to see the full example.</p>
<h4>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/vue-3-basics-program-easily-d5r06?autoresize=1&amp;fontsize=14&amp;hidenavigation=1&amp;initialpath=computedsetdemo&amp;view=split&amp;module=%2Fsrc%2Fcomponents%2FComputedSetSample.vue&amp;theme=light" 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>
<ol>
<li>We are using two props initialNumber and incrementBy.</li>
<li>The counter ref created from initialNumber.</li>
<li>
<div>
<div>counterResult having get/set functions where get is used to return current counter value.</div>
</div>
</li>
<li>set function takes an argument and return the increment result</li>
<li>In Template button click, we are setting computed value as follows
<div>
<div><strong>counterResult = incrementBy</strong></div>
</div>
</li>
</ol>
<h2>To move complex template logics</h2>
<p>In Vue.js, we can write expressions in the template. Its the special feature and very convenient for simple operation. Meanwhile when the logic increases, we have to write lot of expressions inside template. It will reduce the readability of template and makes harder to understand. So we can use computed to handle such situations. Note that, here we have to move template expressions logics into computed.</p>
<p>In the below example, the message is reversed inside template expression. For more information, you can refer <a href="https://v3.vuejs.org/guide/template-syntax.html#using-javascript-expressions" target="_blank" rel="noopener">Template Expressions</a></p>
<pre><code class="language-javascript">&lt;template&gt;
  &lt;div&gt;
    &lt;div&gt;Message : {{ message }}&lt;/div&gt;
    &lt;div&gt;Reversed Message : {{ message.split("").reverse().join("") }}&lt;/div&gt;
  &lt;/div&gt;
&lt;/template&gt;</code></pre>
<p>In this case, we are using the JavaScript expressions inside template. At this point it is okay. But when the template logic increases, it makes hard to understand. So we can move this logic as follows,</p>
<pre><code class="language-javascript">&lt;div&gt;Reversed Message : {{ reversedMessage }}&lt;/div&gt;

const reversedMessage = computed(() =&gt; {
      return props.message.split("").reverse().join("");
});</code></pre>
<p>Now, the template logic is implemented in computed.</p>
<h4>Full Example</h4>
<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/vue-3-basics-program-easily-d5r06?autoresize=1&amp;view=split&amp;fontsize=14&amp;hidenavigation=1&amp;initialpath=computedexpdemo&amp;module=%2Fsrc%2Fcomponents%2FComputedExpressionSample.vue&amp;theme=light" sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"></iframe></h2>
<h2>Computed Caching</h2>
<p>Instead of computed, we can achieve the above logic by using method option also.</p>
<pre><code class="language-javascript">methods: {
    reversedMessage : () =&gt; {
      return this.message.split("").reverse().join("");
    }
  },</code></pre>
<p>In the above example, we are using method instead of computed. Indeed, the end results are same. Then what&#8217;s the difference ? which one is preferable ?. The difference is, computed are cached by nature based on their reactive dependencies. <strong>The computed logic re-executed only when it&#8217;s reactive variable changes</strong>. However The results are cached and immediately return the previously computed value.</p>
<p>Note that, whenever re-render happens, methods will always run the functions irrespective of it&#8217;s reactive dependency changes. So the use case depends on component creator. If we want to cache the result we can go for computed. If we want to run the function for every re-render, always we have to use methods.</p>
<h2>Conclusion</h2>
<p>Among Vue.js six data options, we have learned something about computed property. Some important revisions are,</p>
<ul>
<li>We can use computed for Behavior Dependency and to move complex expression logic from template</li>
<li>It has get, set property. If we give single function, then it will be a get function by default.</li>
<li>Computed are cached by nature. It won&#8217;t always run the function when re-render happens. <strong>The computed logic re-executed only when it&#8217;s reactive variable changes.</strong></li>
</ul>
<p>The post <a rel="nofollow" href="https://programeasily.com/2021/01/30/computed-in-vue-3/">Computed 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/01/30/computed-in-vue-3/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">104</post-id>	</item>
		<item>
		<title>Setup function in Composition API &#8211; Vue 3</title>
		<link>https://programeasily.com/2021/01/04/setup-function-in-composition-api-vue-3/</link>
					<comments>https://programeasily.com/2021/01/04/setup-function-in-composition-api-vue-3/#respond</comments>
		
		<dc:creator><![CDATA[Admin]]></dc:creator>
		<pubDate>Mon, 04 Jan 2021 17:56:19 +0000</pubDate>
				<category><![CDATA[Vuejs]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[vue3]]></category>
		<category><![CDATA[vuejs]]></category>
		<guid isPermaLink="false">http://programeasily.com/?p=148</guid>

					<description><![CDATA[<p>In Vue.js 2, Component objects could have data, computed, methods, and watch options. We will be using these options to write component functional logics. But when our component grows bigger, the functional logic also grows. So we end up to write the same logic in different options. Meaning that, we have to write some parts in the data options, some parts in the methods and others(computed, watch) also. So it will be difficult to understand the component core logics, Since...</p>
<p class="read-more"><a class="btn btn-default" href="https://programeasily.com/2021/01/04/setup-function-in-composition-api-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/01/04/setup-function-in-composition-api-vue-3/">Setup function in Composition API &#8211; Vue 3</a> appeared first on <a rel="nofollow" href="https://programeasily.com">Program Easily</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-159" src="https://i0.wp.com/programeasily.com/wp-content/uploads/2021/01/vue-setup-function-composition-api.jpg?resize=640%2C374" alt="Setup Function in Composition API - VUE 3" width="640" height="374" srcset="https://i0.wp.com/programeasily.com/wp-content/uploads/2021/01/vue-setup-function-composition-api.jpg?w=1920&amp;ssl=1 1920w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/01/vue-setup-function-composition-api.jpg?resize=300%2C175&amp;ssl=1 300w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/01/vue-setup-function-composition-api.jpg?resize=1024%2C598&amp;ssl=1 1024w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/01/vue-setup-function-composition-api.jpg?resize=768%2C449&amp;ssl=1 768w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/01/vue-setup-function-composition-api.jpg?resize=1536%2C898&amp;ssl=1 1536w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/01/vue-setup-function-composition-api.jpg?resize=462%2C270&amp;ssl=1 462w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/01/vue-setup-function-composition-api.jpg?w=1280&amp;ssl=1 1280w" sizes="auto, (max-width: 640px) 100vw, 640px" data-recalc-dims="1" /></p>
<p>In Vue.js 2, Component objects could have data, computed, methods, and watch options. We will be using these options to write component functional logics. But when our component grows bigger, the functional logic also grows. So we end up to write the same logic in different options. Meaning that, we have to write some parts in the data options, some parts in the methods and others(computed, watch) also. So it will be difficult to understand the component core logics, Since it has been written in different places.</p>
<p>Finally, Vue.js 3 introduced a Composition API where we can solve such problems. In Composition API, we can write or composite all options logics(data, computed, methods, watch) in a single place.</p>
<p>In Composition API, we call this place the <span style="color: #008000;"><em>setup</em></span>. We can composite or write all component core logics in the setup function. Here we can organize single core logics even for the complex components. It will be very helpful to read about <a href="http://programeasily.com/2020/12/31/single-file-components-vue-3/" target="_blank" rel="noopener">Single File Components in Vue 3</a> before moving to setup functions in this session. Let&#8217;s take the deep dive!</p>
<h2>Setup function in Composition API</h2>
<p>setup function is the entry point in the Composition API. It will be called before the component is created and after the props are prepared. Meaning that, before compiling and processing it&#8217;s template into a render object. Setup function is called before the beforeCreate hook. Note that <strong>this </strong>reference won&#8217;t be available inside the setup function. Because the component is not created yet.</p>
<p>Next we are going to see how to use the setup function. The <strong>setup</strong> is the function with two arguments(props and context). Anything returned from the setup function will be available throughout our component. In Addition to that It will be accessible inside the template also. Let me explain the same with the below example.</p>
<h2>Setup Function syntax with example</h2>
<p>CustomButton.vue</p>
<pre><code class="language-javascript">&lt;template&gt;
  &lt;div&gt;
    &lt;button&gt;
      {{ label }}
    &lt;/button&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
export default {
  props: {
    label: String,
  },
  setup(props) {
    console.log(props); // { label: '' }
    
    // Write Component Core Logics here
    
    // Anything returned from setup function will be
    // available throughout our component
    return {};
  },
  // return object from setup function accessible here
};
&lt;/script&gt;
</code></pre>
<h2>Setup function in Composition API &#8211; Arguments</h2>
<p>Setup function has two arguments,</p>
<ol>
<li>props</li>
<li>context</li>
</ol>
<p>Let&#8217;s see how these arguments are being used in the components.</p>
<h3>Props</h3>
<p>Props is the first argument of setup function, which are reactive by nature. So while we update the props, the component will be updated. The basic example as follows,</p>
<pre><code class="language-javascript">export default {
  props: {
    label: String,
  },
  setup(props) {
    console.log(props.label);

  },
  
};</code></pre>
<h3 id="props">Props with ES6 Destructive</h3>
<p>Note that props are reactive by default. So we can not use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring" target="_blank" rel="noopener">Object destructuring</a> since it will remove reactive property. We can solve such problems using <a href="https://v3.vuejs.org/api/refs-api.html#torefs" target="_blank" rel="noopener">toRefs</a>. toRefs is useful when the reactive objects are being destructure/spread.</p>
<pre><code class="language-javascript">import { toRefs } from "vue";
export default {
  props: {
    label: String,
  },
  setup(props) {
    const { label } = toRefs(props);
    console.log(label.value);
  },
};</code></pre>
<p>Note that, if label is an optional prop, then toRefs will not create a reactive reference for the label. Here we are in need to use <a href="https://v3.vuejs.org/api/refs-api.html#toref" target="_blank" rel="noopener">toRef</a> instead of toRefs. Let me show the same with below example,</p>
<pre><code class="language-javascript">import { toRef } from "vue";
export default {
  props: {
    label: String,
  },
  setup(props) {
    const label = toRef(props, "label");
    console.log(label.value);
  },
};</code></pre>
<h3>Context</h3>
<p>Context is the second argument of the setup function which is not reactive by nature. This is the normal JavaScript object. It has three component properties,</p>
<ol>
<li class="language-js">attrs &#8211; Attributes (Non-Reactive)</li>
<li>slots &#8211; Slots (Non-Reactive)</li>
<li>emit &#8211; Method (Emit events)</li>
</ol>
<pre><code class="language-javascript">export default {
  setup(props, context) {
    console.log(context.attrs) // (Non-reactive)

    console.log(context.slots) // (Non-reactive)

    console.log(context.emit) // Emit Events
  }
}</code></pre>
<p>Note that context is not reactive. So we can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring" target="_blank" rel="noopener">Object destructuring</a> here as follows,</p>
<pre><code class="language-javascript">export default {
  setup(props, { attrs, slots, emit }) {
    // write logics here
  }
}</code></pre>
<h2>Setup function with Template</h2>
<p>Properties of props and anything returned from the setup function will be accessible in the component&#8217;s template. Let me explain with the below example,</p>
<p><strong>CustomButton.vue</strong></p>
<pre><code class="language-javascript">&lt;template&gt;
  &lt;div&gt;
    &lt;div&gt;{{ counterMsg.msg }} : {{ counter }}&lt;/div&gt;
    &lt;button @click="() =&gt; counter++"&gt;
      {{ label }}
    &lt;/button&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
import { ref, reactive } from "vue";
export default {
  // props properties accessible to template
  props: {
    label: String,
  },
  setup(props) {
    console.log(props.label);
    const counter = ref(0);
    const counterMsg = reactive({ msg: "Click the Button" });
    // below object accessible to template
    return {
      counter,
      counterMsg,
    };
  },
};
&lt;/script&gt;</code></pre>
<p>In the above example counter, counterMsg are from setup function and label from props which are accessible in the template. Note that when we access the <strong>ref</strong> inside template, it will unwrap the inner value automatically. No need to append <em><strong>.value</strong></em> in the template. For more details you can refer <a href="http://programeasily.com/2020/12/17/ref-vs-reactive-in-vue-3/" target="_blank" rel="noopener">Ref vs Reactive in Vue 3</a></p>
<h2>Setup function with render { h }</h2>
<p>As same as with template, we can use setup with render functions also. Here we will be using <a href="https://v3.vuejs.org/guide/render-function.html#render-functions" target="_blank" rel="noopener"><strong>h</strong></a> instead of template in the component. Let me explain with below example,</p>
<p><strong>CustomButton.vue</strong></p>
<pre><code class="language-javascript">&lt;script&gt;
import { ref, reactive, h } from "vue";
export default {
  // props properties accessible to template
  props: {
    label: String,
  },
  setup(props) {
    console.log(props.label);
    const counter = ref(0);
    const counterMsg = reactive({ msg: "Click the Button" });
    // Note that we have to give ref value in in render function
    return () =&gt;
      h(
        "div",
        null,
        counterMsg.msg + ":" + counter.value,
        h(
          "button",
          {
            onClick: () =&gt; counter.value++,
          },
          props.label
        )
      );
  },
};
&lt;/script&gt;</code></pre>
<p>In the above example, the same component has been implemented using the render function. We can convert our template into render function (h) using <a href="https://v3.vuejs.org/guide/render-function.html#template-compilation" target="_blank" rel="noopener">Template Compilation</a></p>
<h2>Conclusion</h2>
<p>So we have learned about <strong><em>setup</em></strong> functions today. Composition API is the fundamental concept of Vue3. The ultimate goal of composition API is to organize the complex component logics in the single place. Typically the place is nothing but the setup function. Another important point is <strong><em>this</em></strong> won&#8217;t be available here unlike other options in the component.</p>
<p>The post <a rel="nofollow" href="https://programeasily.com/2021/01/04/setup-function-in-composition-api-vue-3/">Setup function in Composition API &#8211; 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/01/04/setup-function-in-composition-api-vue-3/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">148</post-id>	</item>
		<item>
		<title>Single File Components Vue 3</title>
		<link>https://programeasily.com/2020/12/31/single-file-components-vue-3/</link>
					<comments>https://programeasily.com/2020/12/31/single-file-components-vue-3/#respond</comments>
		
		<dc:creator><![CDATA[Admin]]></dc:creator>
		<pubDate>Thu, 31 Dec 2020 10:42:25 +0000</pubDate>
				<category><![CDATA[Vuejs]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[vue3]]></category>
		<category><![CDATA[vuejs]]></category>
		<guid isPermaLink="false">http://programeasily.com/?p=126</guid>

					<description><![CDATA[<p>We have learned about components in Components in Vue3 . Here, the components can be registered using either global or local registration. These syntax are designed to suit small sized projects. But when it comes to large sized projects, below problems may happen, Unique component name for each component Since template type is string, poor look for large size templates Failed to apply syntax highlights for template Html(template string) and JavaScript are placed into component objects where CSS left out....</p>
<p class="read-more"><a class="btn btn-default" href="https://programeasily.com/2020/12/31/single-file-components-vue-3/"> Read More<span class="screen-reader-text">  Read More</span></a></p>
<p>The post <a rel="nofollow" href="https://programeasily.com/2020/12/31/single-file-components-vue-3/">Single File Components Vue 3</a> appeared first on <a rel="nofollow" href="https://programeasily.com">Program Easily</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>We have learned about components in <a href="http://programeasily.com/2020/12/22/components-in-vue3/" target="_blank" rel="noopener">Components in Vue3</a> . Here, the components can be registered using either global or local registration. These syntax are designed to suit small sized projects. But when it comes to large sized projects, below problems may happen,</p>
<ol>
<li>Unique component name for each component</li>
<li>Since template type is string, poor look for large size templates</li>
<li>Failed to apply syntax highlights for template</li>
<li>Html(template string) and JavaScript are placed into component objects where CSS left out.</li>
</ol>
<p>So a single file component(SFC&#8217;s) is the solution for above problems with .vue extension. Note that build tools like Webpack are used to parse and compile the .vue file.</p>
<figure id="attachment_140" aria-describedby="caption-attachment-140" style="width: 1920px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" class="wp-image-140 size-full" src="https://i0.wp.com/programeasily.com/wp-content/uploads/2020/12/vue-sfc.jpg?resize=640%2C335" alt="Single File Components in Vue 3" width="640" height="335" srcset="https://i0.wp.com/programeasily.com/wp-content/uploads/2020/12/vue-sfc.jpg?w=1920&amp;ssl=1 1920w, https://i0.wp.com/programeasily.com/wp-content/uploads/2020/12/vue-sfc.jpg?resize=300%2C157&amp;ssl=1 300w, https://i0.wp.com/programeasily.com/wp-content/uploads/2020/12/vue-sfc.jpg?resize=1024%2C537&amp;ssl=1 1024w, https://i0.wp.com/programeasily.com/wp-content/uploads/2020/12/vue-sfc.jpg?resize=768%2C402&amp;ssl=1 768w, https://i0.wp.com/programeasily.com/wp-content/uploads/2020/12/vue-sfc.jpg?resize=1536%2C805&amp;ssl=1 1536w, https://i0.wp.com/programeasily.com/wp-content/uploads/2020/12/vue-sfc.jpg?resize=515%2C270&amp;ssl=1 515w, https://i0.wp.com/programeasily.com/wp-content/uploads/2020/12/vue-sfc.jpg?w=1280&amp;ssl=1 1280w" sizes="auto, (max-width: 640px) 100vw, 640px" data-recalc-dims="1" /><figcaption id="caption-attachment-140" class="wp-caption-text">Single File Components in Vue 3</figcaption></figure>
<h2>Single file Components &#8211; SFC&#8217;s Syntax</h2>
<p>SFC&#8217;s has three parts in the .vue file which are,</p>
<ol>
<li>Template &#8211; HTML design of the component.</li>
<li>JavaScript &#8211; Supports common JS modules.</li>
<li>CSS &#8211; Scoped CSS which <span style="font-weight: 400;">applies </span> to <span style="font-weight: 400;">elements of components</span> alone.</li>
</ol>
<p><strong>Component.Vue</strong></p>
<pre><code class="language-javascript">&lt;template&gt;
  &lt;div&gt;
    &lt;!-- Write HTML for the component here --&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
// Write JavaScript for the component here
&lt;/script&gt;

&lt;style scoped&gt;
/* Write CSS for the Component here.*/
/* Note that scoped attribute, apply css 
to this component HTML element only  */
&lt;/style&gt;</code></pre>
<p>Looks so pretty right!. The Single File Component in Vue.js makes the component so simple to use. And also it solved the problems that occurred in normal components.</p>
<ul>
<li>The HTML elements of the component are much simplified now.</li>
<li>You can use syntax highlights for template ( I preferred <a href="https://vuejs.github.io/vetur/guide/highlighting.html" target="_blank" rel="noopener">Vetur</a>).</li>
<li>JavaScript part of the component are separated rather than insisting the same in the component object.</li>
<li>Scoped CSS is introduced where its CSS apply to the component template HTML element.</li>
</ul>
<h2>Single file Components &#8211; SFC&#8217;s Example</h2>
<p>Now, we are going to create a simple button component using SFC&#8217;s. Button Component has two props namely color and label.</p>
<p>CustomButton.vue</p>
<pre><code class="language-javascript">&lt;template&gt;
  &lt;div class="btn-root"&gt;
    &lt;button class="btn-custom" :style="{ color: color }"&gt;
      {{ label }}
    &lt;/button&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
export default {
  props: {
    color: String,
    label: {
      type: String,
      required: true,
      default: "none",
      validator: function (value) {
        // should return true, if the prop is valid
        return !!value;
      },
    },
  },
};
&lt;/script&gt;

&lt;style scoped&gt;
.btn-custom {
  width: 200px;
  height: 50px;
}
.btn-root {
  margin: 8px;
}
&lt;/style&gt;
</code></pre>
<p><span style="font-weight: 400;">Now we are going to use the CustomButton Component in our Application. Let me show you with the below example !</span></p>
<p>App.vue</p>
<pre><code class="language-javascript">&lt;template&gt;
  &lt;div&gt;
    &lt;CustomButton color="red" label="Red Button" /&gt;
    &lt;CustomButton color="green" label="Green Button" /&gt;
    &lt;CustomButton color="blue" label="Blue Button" /&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
import CustomButton from "./components/CustomButton";
export default {
  components: {
    CustomButton,
  },
};
&lt;/script&gt;</code></pre>
<p>So we have created different colored buttons with different labels using CustomButton Components.</p>
<h2>Single file Components &#8211; SFC&#8217;s Vue Loader</h2>
<p><span style="font-weight: 400;">Indeed, three types of single file components are processed by a vue loader. vue-loader parses the SFC&#8217;s file, extracts each language block and finally computes them into ES modules which is nothing but the Vue.js component option object.</span></p>
<p>vue-loader also supports non default languages like CSS pre-processors and compiles them into HTML. For example we can use Sass in our component to style the elements by specifying the attribute in the CSS block as below,</p>
<pre><code class="language-css">&lt;style lang="sass"&gt;
  /* you can write Sass here! */
&lt;/style&gt;</code></pre>
<h3>Template Block</h3>
<ul>
<li>Each .vue file may contain template blocks.</li>
<li>The template will be passed to <a href="https://www.npmjs.com/package/vue-template-compiler" target="_blank" rel="noopener">vue-template-compiler</a> where the content is compiled into JavaScript render functions and injected in the component script block.</li>
</ul>
<h3>Script Block</h3>
<ul>
<li>Each .vue file may contain a script block.</li>
<li>The plain object or constructor created by Vue.extend is supported, but exporting the object should be a <a href="https://vuejs.org/v2/api/#Options-Data" target="_blank" rel="noopener">component options object</a>.</li>
</ul>
<h3>Style Block</h3>
<ul>
<li>Each .vue file may contain style block</li>
<li>The style tag may have scoped, modules or mixed tags in the same component. Default lang attribute is CSS.</li>
</ul>
<h2>Scoped CSS &#8211; Special Feature</h2>
<p>Using scoped attributes in the style tag, the CSS will be applied to the current component only. Let me explain the same using below example,</p>
<pre><code class="language-markup">&lt;div&gt;
  &lt;div class="btn-root" data-v-75f860b3=""&gt;
    &lt;button class="btn-custom" data-v-75f860b3="" style="color: red;"&gt;
      Red Button&lt;/button&gt;
  &lt;/div&gt;
  &lt;div class="btn-root" data-v-75f860b3=""&gt;
    &lt;button class="btn-custom" data-v-75f860b3="" style="color: green;"&gt;
      Green Button&lt;/button&gt;
  &lt;/div&gt;
  &lt;div class="btn-root" data-v-75f860b3=""&gt;
    &lt;button class="btn-custom" data-v-75f860b3="" style="color: blue;"&gt;
      Blue Button
    &lt;/button&gt;
  &lt;/div&gt;
&lt;/div&gt;
&lt;style type="text/css"&gt;
  .btn-custom[data-v-75f860b3] {
    width: 200px;
    height: 50px;
  }

  .btn-root[data-v-75f860b3] {
    margin: 8px;
  }
&lt;/style&gt;</code></pre>
<p>Note that id <em><span style="color: #008000;">data-v-75f860b3</span></em>  is generated using PostCSS. So the style will be applied to this component alone. At the same time if we want to use styles as globally, we can use global styles as like below</p>
<pre><code class="language-markup">&lt;style&gt;
/* global styles */
&lt;/style&gt;

&lt;style scoped&gt;
/* local styles */
&lt;/style&gt;</code></pre>
<p><span style="font-weight: 400;">Here global style is not scoped which means it will be available throughout our application.</span></p>
<h2>Conclusion</h2>
<p><span style="font-weight: 400;">So SFC&#8217;s single file component is the very special feature in the Vue.js framework. It will ease the Component structure by segregating components into three parts (template, script, style). Unlike global/ local registered components, SFC&#8217;s are well suited for large sized applications.</span></p>
<p>The post <a rel="nofollow" href="https://programeasily.com/2020/12/31/single-file-components-vue-3/">Single File Components Vue 3</a> appeared first on <a rel="nofollow" href="https://programeasily.com">Program Easily</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://programeasily.com/2020/12/31/single-file-components-vue-3/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">126</post-id>	</item>
		<item>
		<title>Components in Vue 3</title>
		<link>https://programeasily.com/2020/12/22/components-in-vue-3/</link>
					<comments>https://programeasily.com/2020/12/22/components-in-vue-3/#respond</comments>
		
		<dc:creator><![CDATA[Admin]]></dc:creator>
		<pubDate>Tue, 22 Dec 2020 17:20:30 +0000</pubDate>
				<category><![CDATA[Vuejs]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[vue3]]></category>
		<category><![CDATA[vuejs]]></category>
		<guid isPermaLink="false">http://programeasily.com/?p=39</guid>

					<description><![CDATA[<p>As programmers, we all know that reusing logic and source code as much as possible is the best practice. Note that, sometimes we have to write complex HTML ( including style, script ) to render UI and we end up using the same logic multiple times which can turn our pages into a mess. Components in the programming world aim to solve such problems. It aims, Splitting UI into reusable pieces and each piece responsible for a small set of...</p>
<p class="read-more"><a class="btn btn-default" href="https://programeasily.com/2020/12/22/components-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/2020/12/22/components-in-vue-3/">Components in Vue 3</a> appeared first on <a rel="nofollow" href="https://programeasily.com">Program Easily</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>As programmers, we all know that reusing logic and source code as much as possible is the best practice. Note that, sometimes we have to write complex HTML ( including style, script ) to render UI and we end up using the same logic multiple times which can turn our pages into a mess.</p>
<p>Components in the programming world aim to solve such problems. It aims, Splitting UI into reusable pieces and each piece responsible for a small set of core logic that encapsulates as reusable code.</p>
<p>In Vue.js components are the most important and powerful feature. we can abstract large application interfaces into small reusable components. Let&#8217;s take a deep dive!</p>
<figure id="attachment_113" aria-describedby="caption-attachment-113" style="width: 1280px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" class="wp-image-113 size-full" src="https://i0.wp.com/programeasily.com/wp-content/uploads/2020/12/infographic-5388658_1280-1.png?resize=640%2C427&#038;ssl=1" alt="Reusable Components in Vue 3" width="640" height="427" srcset="https://i0.wp.com/programeasily.com/wp-content/uploads/2020/12/infographic-5388658_1280-1.png?w=1280&amp;ssl=1 1280w, https://i0.wp.com/programeasily.com/wp-content/uploads/2020/12/infographic-5388658_1280-1.png?resize=300%2C200&amp;ssl=1 300w, https://i0.wp.com/programeasily.com/wp-content/uploads/2020/12/infographic-5388658_1280-1.png?resize=1024%2C682&amp;ssl=1 1024w, https://i0.wp.com/programeasily.com/wp-content/uploads/2020/12/infographic-5388658_1280-1.png?resize=768%2C512&amp;ssl=1 768w, https://i0.wp.com/programeasily.com/wp-content/uploads/2020/12/infographic-5388658_1280-1.png?resize=405%2C270&amp;ssl=1 405w" sizes="auto, (max-width: 640px) 100vw, 640px" data-recalc-dims="1" /><figcaption id="caption-attachment-113" class="wp-caption-text">Components in Vue 3</figcaption></figure>
<h2>Components in Vue 3</h2>
<p>Almost any type of application can be abstracted or organized into a group of components. For example in our application design, we are having header, footer, menu, content area etc. Here we can create each piece as a component and organize all into a single core as a page effectively.</p>
<p>In Vue.js, components are reusable instances and that can be created with the below anatomy.</p>
<h3>Component Anatomy</h3>
<pre><code class="language-javascript">import { createApp } from "vue";
import App from "./App.vue";

const customComponent = {
  components: {
    // mention sub components, if we used in the template
  },
  // the parameters which component accepts
  props: {
    color: String,
    label: {
      type: String,
      required: true,
      default: "none",
      validator: function(value) {
        // should return true, if the prop is valid
        return !!value;
      },
    },
  },
  // the reusable html element
  template: `&lt;button :style="{ color: color }"&gt;
          {{ label }}
          &lt;/button&gt;`,
};
const app = createApp(App);
// register the component globally
app.component("CustomButton", customComponent);
app.mount("#app");</code></pre>
<p>Here, we have created a Vue.js component named <strong>CustomButton</strong>. The component object has below properties,</p>
<ol>
<li>components &#8211; mention sub components</li>
<li>props &#8211; the parameters component accepts</li>
<li>template &#8211; html element</li>
</ol>
<p>In Addition, <a href="https://v3.vuejs.org/api/composition-api.html#setup">setup</a> hook plays a major role. You can learn about it from <a href="https://programeasily.com/2021/01/04/setup-function-in-composition-api-vue-3/" target="_blank" rel="noopener">Setup function in Composition API – Vue 3</a> topic.</p>
<h3>Reusable Components in Vue 3</h3>
<p>We can reuse <strong>CustomButton </strong>based on our needs.</p>
<pre><code class="language-">&lt;template&gt;
  &lt;div&gt;
    &lt;CustomButton label="Red" color="red" /&gt; // create red button
    &lt;CustomButton label="Green" color="green" /&gt; // create green button
    &lt;CustomButton label="Blue" color="blue" /&gt; // create blue button
  &lt;/div&gt;
&lt;/template&gt;</code></pre>
<p>In the above example, we are passing prop attributes( label, color ). The prop attributes will become property of the component instance. So the props are accessible inside the template tag.</p>
<p>Note that, each component maintain its own state. it&#8217;s because whenever we use the components, a new instance created for the same.</p>
<h2 id="global-registration">Global Registration</h2>
<p>Here the components registered globally for the application which means it can be used in any template of the application.</p>
<pre><code class="language-javascript">const app = Vue.createApp({})

app.component('add-button', {
  /* ... */
})
app.component('save-button', {
  /* ... */
})
app.component('delete-button', {
  /* ... */
})

app.mount('#app')</code></pre>
<p>So we can use above component in any template of our application now,</p>
<pre><code class="language-markup">&lt;div id="app"&gt;
  &lt;add-button&gt;&lt;/add-button&gt;
  &lt;save-button&gt;&lt;/save-button&gt;
  &lt;delete-button&gt;&lt;/delete-button&gt;
&lt;/div&gt;</code></pre>
<h2 id="local-registration">Local Registration</h2>
<p>In the real time project, global registration is not preferred. Because if we are using a build system like <a href="https://webpack.js.org/">Webpack</a>, global registration loads all components in the build irrespective of component usage in our application. This will increase the script file size unnecessarily.</p>
<p>So Vue.js introduced local registration for components. Here we can create plain objects as like below first ,</p>
<pre><code class="language-javascript">const ComponentOne = {
  /* ... */
}
const ComponentTwo = {
  /* ... */
}
const ComponentThree = {
  /* ... */
}</code></pre>
<p>Next, we have to map above object to component property in the Vue.js application instance as like below,</p>
<pre><code class="language-javascript">const app = Vue.createApp({
  components: {
    'component-one': ComponentOne,
    'component-two': ComponentTwo,
    'component-three': ComponentThree
  }
})</code></pre>
<p>Here another important point is, local registered components not available in our subcomponents. Let me explain with the below example, Here <strong>ComponentOne </strong>used in ComponentTwo so we have to mention the same in ComponentTwo Object.</p>
<pre><code class="language-javascript">const ComponentOne = {
  /* ... */
}

const ComponentTwo = {
  components: {
    'component-one': ComponentOne
  }
  // ...
}</code></pre>
<h2 id="local-registration">Custom Events in Components Vue 3</h2>
<blockquote>
<pre>Children - Emit the event

Parent - Listen to the event</pre>
</blockquote>
<p>Custom events are another interesting topic of Vue.js Components. In the component hierarchy some time we came up to communicate back to the parent from child component. In that situation, Parent listen to any events from the child where the child emits the event.</p>
<h3 id="single-file-components">Emit event in the Child.vue</h3>
<div>
<blockquote>
<div>&lt;button @click=&#8221;$emit(&#8216;/** custom event name **/&#8217;)&#8221; /&gt;</div>
<div>&lt;button @click=&#8221;$emit(&#8216;btn_click&#8217;)&#8221; /&gt;</div>
</blockquote>
<h3>Listen to the event in Parent.vue</h3>
<div>
<blockquote>
<div>&lt;Child @/** custom event name **/=&#8221;/** event callback method **/&#8221;</div>
<div>&lt;Child @btn_click=&#8221;onBtnClickCallback&#8221;</div>
</blockquote>
<h2>Conclusion</h2>
<p>So component helps widely when we build large scale applications. Reusable sources is the main objective of any component rather than Vue.js Components. Note that, the common application can be organized into nested components which means every part of the page is component here. That&#8217;s the power of component function!.</p>
</div>
</div>
<p>The post <a rel="nofollow" href="https://programeasily.com/2020/12/22/components-in-vue-3/">Components 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/2020/12/22/components-in-vue-3/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">39</post-id>	</item>
		<item>
		<title>Ref vs Reactive in Vue 3</title>
		<link>https://programeasily.com/2020/12/17/ref-vs-reactive-in-vue-3/</link>
					<comments>https://programeasily.com/2020/12/17/ref-vs-reactive-in-vue-3/#respond</comments>
		
		<dc:creator><![CDATA[Admin]]></dc:creator>
		<pubDate>Thu, 17 Dec 2020 18:55:05 +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=31</guid>

					<description><![CDATA[<p>Today in the modern world, many JavaScript frameworks having their own reactive engines. Among them Vue&#8217;s defined special features is reactive system. The plain JavaScript object changes are tracked and when we modify it, the view gets updated. In Vue the reactive conversion affects all its nested children properties. Ref and Reactive both provides a way to store object data and allow that object to be reactive. So today we are going to discuss how this two helps and plays...</p>
<p class="read-more"><a class="btn btn-default" href="https://programeasily.com/2020/12/17/ref-vs-reactive-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/2020/12/17/ref-vs-reactive-in-vue-3/">Ref vs Reactive in Vue 3</a> appeared first on <a rel="nofollow" href="https://programeasily.com">Program Easily</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Today in the modern world, many JavaScript frameworks having their own reactive engines. Among them Vue&#8217;s defined special features is reactive system. The plain JavaScript object changes are tracked and when we modify it, the view gets updated.</p>



<p>In Vue the reactive conversion affects all its nested children properties. <strong>Ref and Reactive</strong> both provides a way to store object data and allow that object to be reactive. So today we are going to discuss how this two helps and plays major rule in a Vue&#8217;s reactive world. Lets take a deep dive!</p>



<figure class="wp-block-image size-large is-style-default"><img loading="lazy" decoding="async" width="640" height="425" src="https://i0.wp.com/programeasily.com/wp-content/uploads/2020/12/computer-1245714_1920-1024x680.jpg?resize=640%2C425" alt="ref vs reactive" class="wp-image-56" srcset="https://i0.wp.com/programeasily.com/wp-content/uploads/2020/12/computer-1245714_1920.jpg?resize=1024%2C680&amp;ssl=1 1024w, https://i0.wp.com/programeasily.com/wp-content/uploads/2020/12/computer-1245714_1920.jpg?resize=300%2C199&amp;ssl=1 300w, https://i0.wp.com/programeasily.com/wp-content/uploads/2020/12/computer-1245714_1920.jpg?resize=768%2C510&amp;ssl=1 768w, https://i0.wp.com/programeasily.com/wp-content/uploads/2020/12/computer-1245714_1920.jpg?resize=1536%2C1020&amp;ssl=1 1536w, https://i0.wp.com/programeasily.com/wp-content/uploads/2020/12/computer-1245714_1920.jpg?resize=407%2C270&amp;ssl=1 407w, https://i0.wp.com/programeasily.com/wp-content/uploads/2020/12/computer-1245714_1920.jpg?w=1920&amp;ssl=1 1920w, https://i0.wp.com/programeasily.com/wp-content/uploads/2020/12/computer-1245714_1920.jpg?w=1280&amp;ssl=1 1280w" sizes="auto, (max-width: 640px) 100vw, 640px" data-recalc-dims="1" /><figcaption>Ref vs Reactive in Vue3</figcaption></figure>



<h2 class="wp-block-heading">Ref</h2>



<p>It takes an primitives argument and return a reactive mutable object. The object has single property &#8216;value&#8217; and it will point to the argument taken by it.</p>



<pre class="wp-block-preformatted">const increment = ref(0);
console.log(increment.value) // 0

<code>increment.value++</code>;
<code>console.log(increment.value) // 1</code></pre>



<h3 class="wp-block-heading" id="block-e31ff1f9-e784-410e-a0ff-cb051b74ba8b">Within Template</h3>



<p>when we access <strong>ref</strong> inside template, it will unwrap the inner value automatically. No need to append .value in the template. <strong>Ref</strong> should be return as a property of setup hook(render context).</p>



<pre class="wp-block-preformatted">&lt;template&gt;
&nbsp;&nbsp;&lt;div&gt;{{&nbsp;state&nbsp;}}&lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
<em>import</em>&nbsp;{&nbsp;ref&nbsp;}&nbsp;<em>from</em>&nbsp;'vue';
&nbsp;&nbsp;<em>export</em>&nbsp;<em>default</em>&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;<em>setup</em>()&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<em>return</em>&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;state:&nbsp;<em>ref</em>('Hello&nbsp;World...')
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;}
&lt;/script&gt;</pre>



<h3 class="wp-block-heading">Within Reactive Object</h3>



<p>when we pass <strong>ref</strong> as a argument to reactive object, it automatically unwraps its inner value. <strong>ref</strong> unwrapping won&#8217;t happens for Array, Map.</p>



<pre class="wp-block-code"><code>const increment = ref(0)
const state = reactive({
  increment
})

console.log(state.increment) // 0

state.increment = 1
console.log(count.increment) // 1</code></pre>



<h2 class="wp-block-heading">Reactive</h2>



<p>It takes a JavaScript object as a argument and returns <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy">Proxy</a> based reactive copy of the object.</p>



<pre class="wp-block-code"><code>const state = reactive({
name : 'john',
age  : 21
});</code></pre>



<p>we have to note that, the returned proxy is not same as original object. so in-terms of identity === comparison will be failed.</p>



<h3 class="wp-block-heading">Reactive within template</h3>



<pre id="block-92a41b9f-e6ad-4411-968b-82d66ef4ca26" class="wp-block-preformatted">&lt;template&gt;
&nbsp;&nbsp;&lt;div&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&lt;div&gt;&nbsp;User&nbsp;Name&nbsp;:&nbsp;{{&nbsp;<em>state.</em>name&nbsp;}}&lt;/div&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&lt;div&gt;Age&nbsp;:&nbsp;{{&nbsp;<em>state.</em>age&nbsp;}}&lt;/div&gt;
&nbsp;&nbsp;&lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
<em>import</em>&nbsp;{&nbsp;reactive&nbsp;}&nbsp;<em>from</em>&nbsp;'vue';
<em>export</em>&nbsp;<em>default</em>&nbsp;{
&nbsp;&nbsp;<em>setup</em>()&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;const<em>&nbsp;state&nbsp;</em>=<em>&nbsp;reactive</em>({
<em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;name</em>:<em>&nbsp;</em>"john",
<em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;age</em>:<em>&nbsp;</em>21,
<em>&nbsp;&nbsp;&nbsp;&nbsp;</em>});
&nbsp;&nbsp;&nbsp;&nbsp;<em>return</em>&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;state,
&nbsp;&nbsp;&nbsp;&nbsp;};
&nbsp;&nbsp;},
};
&lt;/script&gt;
</pre>



<h2 class="wp-block-heading">Ref vs Reactive</h2>



<p>Typically, <strong>ref</strong> and <strong>reactive</strong> both have been used to create reactive objects where <strong>ref</strong> is used to make the primitive values to be reactive (<em>Boolean, Number</em>, <em>String</em>). But <strong>reactive</strong> won&#8217;t work with primitives rather than it works for objects.</p>



<p>Here the problem with <strong>reactive</strong> is the returned object of setup hook cannot be destructured or spread. To solve this issue Vue introduced <em><strong>toRefs</strong></em> which converts each property on a reactive object into ref object. So we have to remember to use <em><strong>toRefs</strong></em> with <em>reactive</em> when we returning the <em>reactive</em> proxy object from setup hook (composite functions)</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="640" height="303" src="https://i0.wp.com/programeasily.com/wp-content/uploads/2020/12/refreactive.png?resize=640%2C303&#038;ssl=1" alt="Difference Between Ref and Reactive in Vue3" class="wp-image-67" title="Ref Vs Reactive - Vue3" srcset="https://i0.wp.com/programeasily.com/wp-content/uploads/2020/12/refreactive.png?w=957&amp;ssl=1 957w, https://i0.wp.com/programeasily.com/wp-content/uploads/2020/12/refreactive.png?resize=300%2C142&amp;ssl=1 300w, https://i0.wp.com/programeasily.com/wp-content/uploads/2020/12/refreactive.png?resize=768%2C364&amp;ssl=1 768w, https://i0.wp.com/programeasily.com/wp-content/uploads/2020/12/refreactive.png?resize=570%2C270&amp;ssl=1 570w" sizes="auto, (max-width: 640px) 100vw, 640px" data-recalc-dims="1" /><figcaption>Ref vs Reactive &#8211; Vue3</figcaption></figure>



<h2 class="wp-block-heading">Summary</h2>



<p>So <strong>ref / reactive</strong> both are been used to create reactive object where the changes been tracked. The DOM will get updated only when there is a change in reactive objects. This is the fundamental understanding!. </p>



<p></p>
<p>The post <a rel="nofollow" href="https://programeasily.com/2020/12/17/ref-vs-reactive-in-vue-3/">Ref vs Reactive 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/2020/12/17/ref-vs-reactive-in-vue-3/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">31</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 19/55 queries in 0.080 seconds using disk (Request-wide modification query)

Served from: programeasily.com @ 2025-06-20 07:57:45 by W3 Total Cache
-->