<?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>Admin, Author at Program Easily</title>
	<atom:link href="https://programeasily.com/author/admin/feed/" rel="self" type="application/rss+xml" />
	<link>https://programeasily.com/author/admin/</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>Admin, Author at Program Easily</title>
	<link>https://programeasily.com/author/admin/</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">187075990</site>	<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 fetchpriority="high" 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="(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>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 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="(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>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 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="(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>
		<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 loading="lazy" 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="auto, (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 loading="lazy" 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="auto, (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/60 queries in 0.154 seconds using disk (Request-wide modification query)

Served from: programeasily.com @ 2025-06-20 07:27:04 by W3 Total Cache
-->