<?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>vue3 Archives - Program Easily</title>
	<atom:link href="https://programeasily.com/tag/vue3/feed/" rel="self" type="application/rss+xml" />
	<link>https://programeasily.com/tag/vue3/</link>
	<description>Program Easily helps people to learn about software programs in a easy manner.</description>
	<lastBuildDate>Thu, 15 Dec 2022 03:54:10 +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>vue3 Archives - Program Easily</title>
	<link>https://programeasily.com/tag/vue3/</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">187075990</site>	<item>
		<title>When to use NextTick API in Vue.js</title>
		<link>https://programeasily.com/2022/12/15/when-to-use-nexttick-api-in-vue-js/</link>
					<comments>https://programeasily.com/2022/12/15/when-to-use-nexttick-api-in-vue-js/#respond</comments>
		
		<dc:creator><![CDATA[Admin]]></dc:creator>
		<pubDate>Thu, 15 Dec 2022 03:54:10 +0000</pubDate>
				<category><![CDATA[Vuejs]]></category>
		<category><![CDATA[vue]]></category>
		<category><![CDATA[vue.js]]></category>
		<category><![CDATA[vue3]]></category>
		<guid isPermaLink="false">https://programeasily.com/?p=2042</guid>

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

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

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

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

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

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

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

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

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

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

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

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

store.counter++

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// we can represent above directive as below object

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

// binding value as JavaScript object literal

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

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

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

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

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

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

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

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

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

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