<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Matheus Ricelly on Medium]]></title>
        <description><![CDATA[Stories by Matheus Ricelly on Medium]]></description>
        <link>https://medium.com/@fsenaweb?source=rss-9f0709f6da2c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xm16GD73b1RO3WWysjO2uw.jpeg</url>
            <title>Stories by Matheus Ricelly on Medium</title>
            <link>https://medium.com/@fsenaweb?source=rss-9f0709f6da2c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 12:19:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fsenaweb/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[An Introduction to Hooks in React (useState)]]></title>
            <link>https://javascript.plainenglish.io/introducing-hooks-in-react-usestate-1de8b69adafc?source=rss-9f0709f6da2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1de8b69adafc</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Matheus Ricelly]]></dc:creator>
            <pubDate>Wed, 02 Jun 2021 13:51:59 GMT</pubDate>
            <atom:updated>2021-06-11T11:09:47.374Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introducing Hooks in React (useState)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DklmkzDo8X-qM_fBBwMc_Q.jpeg" /></figure><p>Hello everyone!</p><p>Although hooks are no longer a great novelty within React (since they have been introduced with version 16.8), there is still a large collection of documents that exemplify the traditional model of development through classes in React components.</p><p>I will write a series of introductory articles talking about the main React Hooks, among them, the <strong>useState</strong> (which will be our first), <strong>useEffect,</strong> and <strong>useContext.</strong> Then we will pass through those a little more complex for some users, such as <strong>useRef</strong>, <strong>useCallback</strong>, <strong>useReducer</strong>, among others. You can also create your own hook, this is very useful in certain situations (we can see in the next publication, leave your comment).</p><h3>Theory</h3><h4>What is a hook?</h4><p>Well summarized, a hook is nothing more than a function that gives you access to certain features of a functional component of React (yes, functional component, since hooks do not work within classes), and that way you can access to your state and life cycle.</p><p>And to have a good performance as states and lifecycles are rendered in the component, Hooks have a basic rule that specifies that it should never be used within loops, conditional rules (if, else for example) or nested functions, be aware of this rule!</p><h3>Hands-on</h3><h4>useState</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PgRiXXm1WbeUuJmkwVL6NQ.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab5bcc08237c47740db1364f2cddd1d8/href">https://medium.com/media/ab5bcc08237c47740db1364f2cddd1d8/href</a></iframe><p>This hook is responsible for manipulating the <em>state</em> of your application. It returns to us an array where we have a value and a function that when invoked will have a responsibility to change the information of this value.</p><p>We can pass an initial value when the initial rendering of the component occurs. This value is the same signpost within the initial argument in useState (<strong>initialState</strong>).</p><p>In this example, <strong>setState</strong> is used when we want to update that state variable within the component. It receives the new value informed and instead of updating immediately, it queues that value, thus passing the most recent value to this variable, this process is well known in the react by <strong>immutability</strong>.</p><p>An alternative, and you can find in several codes, is the possibility of invoking the function that updates the status with a callback, taking the same previous example, could refactor it like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tttZDqsJ2oNjuU82jHlk0w.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49926979ccb992f043dc6c5b3c29cb52/href">https://medium.com/media/49926979ccb992f043dc6c5b3c29cb52/href</a></iframe><p>That way the new state based on the previous one returns. Due to immutability, this is widely used in some applications where we want to make some comparisons on state changes for screen animations, for example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b--ZaDxkM51_JKBXjifz2A.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cc0a34beef8d3144435dcffec641607/href">https://medium.com/media/8cc0a34beef8d3144435dcffec641607/href</a></iframe><p>Already when we use the <em>TypeScript</em>, we infer the state type as in the above example useState&lt;string&gt;(&#39;value&#39;). However, it is worth mentioning, that for primary types (such as strings, number, boolean, for example) you do not need to make the type explicit because the typescript interpreter can dynamically define them, leaving that way, the cleaner code Thus avoiding an error if a different data type is informed.</p><p>A more complete example about using type in useState with TypeScript you can be below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f27e7c7eed34dc14d492dda5abee7de/href">https://medium.com/media/8f27e7c7eed34dc14d492dda5abee7de/href</a></iframe><p>Above, very simple, show how to pass an array of products, inside the useState. With this, in addition to testing the use of array (which is another type allowed inside the useState), we can verify how to proceed with this typing through the typescript and infer within the code perform the listing for view on the page.</p><h4>Tips that are essential in using useState</h4><blockquote><em>As good practice, always try to call the useState Hooks at the beginning of the component. Even if you position it in different places, React will try to organize so that your code works, however, you will present several warnings in your devtools.</em></blockquote><blockquote><em>Avoid creating Usestate within loops, conditional or some nested function, this can cause various errors in the rendering of your component, damaging your project.</em></blockquote><p>It’s from this introductory line, that you can deepen a little more of your knowledge within React and React Hooks. Explore your knowledge and studies in this React functionality that allows you to help in various tasks in your applications. You can have all the information about Hooks in <a href="https://reactjs.org/docs/hooks-intro.html">Official Documentation</a> or a <a href="https://reactjs.org/docs/hooks-reference.html#usestate">Detailed Reference of Usestate</a>.</p><p>If you liked this article, be sure to share and comment. If you want to know a little more, change some ideas, you can leave the comments your opinion on the subject and even suggest something for the upcoming articles.</p><p>Enjoy and get to know a little of my jobs, visiting the site <a href="https://www.fsenaweb.me/">www.fsenaweb.me</a>. It’s has my portfolio, my social networks (including <a href="https://github.com/fsenaweb/">GitHub</a>, where you have a few applications of examples to practice), and contacts links.</p><ul><li><a href="https://github.com/fsenaweb">fsenaweb - Overview</a></li><li><a href="https://reactjs.org/docs/hooks-reference.html#usestate">Hooks API Reference - React</a></li><li><a href="https://reactjs.org/docs/hooks-intro.html">Introducing Hooks - React</a></li></ul><p>And that’s it, until next time! My name is <em>Matheus Ricelly</em>, and for his attention, my thank you!</p><p><em>More content at </em><a href="http://plainenglish.io/"><em>plainenglish.io</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1de8b69adafc" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/introducing-hooks-in-react-usestate-1de8b69adafc">An Introduction to Hooks in React (useState)</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introdução aos React Hooks (useState)]]></title>
            <link>https://fsenaweb.medium.com/introdu%C3%A7%C3%A3o-aos-react-hooks-usestate-806f8b76458a?source=rss-9f0709f6da2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/806f8b76458a</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[usestate]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Matheus Ricelly]]></dc:creator>
            <pubDate>Wed, 02 Jun 2021 12:14:45 GMT</pubDate>
            <atom:updated>2021-06-02T12:22:03.467Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introdução aos Hooks no React(useState)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8vjBTvAKJm5rSkg8Vemh1w.jpeg" /></figure><p>Olá Pessoal!</p><p>Apesar dos Hooks não serem mais uma grande novidade dentro do React (pois foram introduzidos desde a versão 16.8), ainda existe um grande acervo de documentos que exemplificam sobre o modelo tradicional de desenvolvimento através de classes nos componentes do React.</p><p>Irei escrever uma série de artigos introdutórios falando sobre os principais Hooks do React, entre eles, o <strong>useState</strong> (que será nosso primeiro), <strong>useEffect</strong> e <strong>useContext</strong>, logo em seguida, passaremos por aqueles um pouco mais complexas para alguns usuários, como <strong>useMemo</strong>, <strong>useRef</strong>, <strong>useCallback</strong>, <strong>useReducer</strong>, entre outros. Você também pode criar seu próprio Hook, isso é muito útil em determinadas situações (poderemos ver numa próxima publicação, deixe o seu comentário).</p><p>Tentarei explicar de uma forma bem introdutória e clara (utilizando exemplos com Javascript e TypeScript), com a intenção de auxiliar aos desenvolvedores que estão iniciando nessa carreira do desenvolvimento front-end com o React (Web e Native) e que pode ser aplicado dentro dos frameworks mais populares como o Gatsby, Next.js e React Native.</p><h3>Teoria</h3><h4>O que é um Hook?</h4><p>De forma bem resumida, um Hook nada mais é que uma função que te dá acesso a determinados recursos de um componente funcional do React (sim, componente funcional, pois os Hooks não funcionam dentro de Classes), e dessa forma, você pode ter acesso ao seu estado e ciclo de vida.</p><p>E para ter uma boa performance da forma como os estados e os ciclos de vida são renderizados no componente, os Hooks tem uma regrinha básica que especifica que nunca deve ser utilizado dentro de loops, regras condicionais (if, else por exemplo) ou funções aninhadas, fique atento a essa regra!</p><h3>Mão na massa</h3><h4>useState</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PgRiXXm1WbeUuJmkwVL6NQ.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab5bcc08237c47740db1364f2cddd1d8/href">https://medium.com/media/ab5bcc08237c47740db1364f2cddd1d8/href</a></iframe><p>Esse Hook é o responsável por manipular o <em>state </em>da sua aplicação. Ele nos retorna um array onde temos um valor e uma função que ao ser invocada terá responsabilidade de alterar a informação desse valor.</p><p>Podemos passar um valor inicial, quando ocorre a renderização inicial do componente. Esse valor é o mesmo sinalizado dentro do argumento inicial em useState(<strong>initialState</strong>).</p><p>Já nesse exemplo, o <strong>setState</strong> é utilizado quando queremos atualizar aquela variável de estado dentro do componente. Ele recebe o novo valor informado e em vez de atualizar de forma imediata, ele enfileira esse valor, passando assim o valor mais recente a essa variável, esse processo é bem conhecido no React por <strong>imutabilidade</strong>.</p><p>Uma outra alternativa, e que poderá encontrar em diversos códigos, é a possibilidade de se invocar a função que atualiza o estado com um retorno de chamada, pegando o mesmo exemplo anterior, poderia refatorá-lo assim:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tttZDqsJ2oNjuU82jHlk0w.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49926979ccb992f043dc6c5b3c29cb52/href">https://medium.com/media/49926979ccb992f043dc6c5b3c29cb52/href</a></iframe><p>Dessa forma retorna-se o novo estado com base no anterior. Devido a imutabilidade, isso é muito utilizado em algumas aplicações onde queremos fazer algumas comparações em mudanças de estado para animações em tela, por exemplo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b--ZaDxkM51_JKBXjifz2A.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cc0a34beef8d3144435dcffec641607/href">https://medium.com/media/8cc0a34beef8d3144435dcffec641607/href</a></iframe><p>Já quando utilizamos o <em>TypeScript</em>, inferimos o tipo do estado como no exemplo acima <strong><em>useState&lt;string&gt;(‘value’)</em></strong>. Porém, vale ressaltar, que para tipos primários (como strings, number, boolean, por exemplo) você não precisa tornar o tipo explícito, pois o interpretador do TypeScript consegue defini-los de forma dinâmica, deixando dessa forma, o código mais limpo e evitando assim um erro caso seja informado um tipo de dado diferente.</p><p>Um exemplo mais completo sobre o uso de tipo no useState com o TypeScript você pode ser abaixo:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56481ce96ab8779e23c10d4aef9dd9c1/href">https://medium.com/media/56481ce96ab8779e23c10d4aef9dd9c1/href</a></iframe><p>Acima, de forma bem simples, mostro como passar um array de produtos, dentro do useState. Com isso, além de testarmos a utilização de Array (que é mais um tipo permitido dentro do useState), podemos verificar como proceder com essa tipagem através do TypeScript e inferir dentro do código realizar a listagem para exibição na página.</p><h3>Dicas que são essenciais no uso do useState</h3><blockquote>Como boa prática, procure sempre chamar os hooks useState no início do componente. Mesmo que você o posicione em locais diferentes, o React irá tentar organizar para que seu código funcione, porém, apresentará diversos warnings em seu DevTools.</blockquote><blockquote>Evite criar useState dentro de loops, condicionais ou em algum função aninhada, isso pode causar diversos erros na renderização do seu componente, prejudicando o seu projeto.</blockquote><p>É a partir dessa linha introdutória, que você poderá aprofundar um pouco mais dos seus conhecimentos dentro do React e o React Hooks. Explore um pouco os seus conhecimentos e estudos nessa funcionalidade do React que te permite ajudar em diversas tarefas nas suas aplicações. Você pode ter todas as informações sobre os Hooks na <a href="https://reactjs.org/docs/hooks-intro.html">documentação oficial</a> ou uma <a href="https://reactjs.org/docs/hooks-reference.html#usestate">referência detalhada do useState</a>.</p><p>Se você está iniciando com React ou já desenvolve há um bom tempo, eu indico um excelente curso, do <strong>Willian Justen</strong>, chamado “React avançado”, onde ele aborda de uma maneira super didática como trabalhar com o React, utilizando conceitos iniciais e avançados, montando um projeto prático, realizando testes unitários, testes de integração e muito mais, vale a pena o investimento. O link você confere no final do artigo.</p><p>Se você gostou desse artigo, não deixe de compartilhar e comentar. Se você quiser saber um pouco mais, trocar algumas idéias, poderá deixar nos comentários sua opinião sobre o assunto e até sugerir algo para os próximos artigos.</p><p>Aproveite e conheça um pouco dos meus trabalhos, visitando o site <a href="https://fsenaweb.me/"><strong><em>www.fsenaweb.me</em></strong></a>. Ele tem o meu portfólio, minhas redes sociais (inclusive o <a href="https://github.com/fsenaweb/">GitHub</a> , onde você tem a disposição algumas aplicações de exemplos para poder praticar), e um pequeno espaço para contatos.</p><ul><li><a href="https://github.com/fsenaweb">fsenaweb - Overview</a></li><li><a href="https://reactjs.org/docs/hooks-reference.html#usestate">Hooks API Reference - React</a></li><li><a href="https://reactjs.org/docs/hooks-intro.html">Introducing Hooks - React</a></li><li><a href="https://reactavancado.com.br/">React Avançado - Crie aplicações reais com NextJS, GraphQL e mais.</a></li></ul><p>E é isso, até a próxima! Meu nome é <em>Matheus Ricelly</em> , e pela sua atenção, o meu <em>muito obrigado</em> !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=806f8b76458a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Knowing and developing filters in Vue.js]]></title>
            <link>https://medium.com/js-dojo/knowing-and-developing-filters-in-vue-js-72c24e492e6c?source=rss-9f0709f6da2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/72c24e492e6c</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[filters]]></category>
            <category><![CDATA[components]]></category>
            <dc:creator><![CDATA[Matheus Ricelly]]></dc:creator>
            <pubDate>Mon, 10 Feb 2020 04:32:11 GMT</pubDate>
            <atom:updated>2020-02-10T04:32:11.848Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*kt9EaMD4DtaJEtiNESPH9g.png" /></figure><p>Hi guys!</p><p>In this article, in a special way, I will talk about a feature that in my opinion is little used (or commented on) within the Vue.js community, which are <strong>Filters</strong>. Like Plugins, Custom Directives and <a href="https://medium.com/javascript-in-plain-english/how-to-work-with-mixins-on-vue-js-a61f72737f25">Mixins</a>, filters are part of the reusable features within Vue, helping in the process of creating components.</p><blockquote>In Vue components, filters are functionalities that allow us to obtain different formats in the output of the dynamic data of its state. That is, they do not change the data of a component, they can only format their data in rendering.</blockquote><h3>Local filters</h3><p>According to the <a href="https://vuejs.org/v2/guide/filters.html">official documentation</a>, the use of filters occurs within mustache interpolations and v-bind expressions. See an example of the formatting of the filter in the template:</p><pre>&lt;!-- in interpolations text --&gt; <br>{{ message | capitalize }}  </pre><pre>&lt;!-- in attribute interconnections --&gt; <br>&lt;div v-bind:text=&quot;message | capitalize&quot;&gt;&lt;/div&gt;</pre><p>Creating locally, within the component, we can have:</p><pre>filters: {<br>   capitalize(value) {<br>     if (!value) return &#39;&#39;<br>     value = value.toString()<br>     return value.charAt(0).toUpperCase() + value.slice(1)<br>   }<br>}</pre><p>In this first example, extracted from the documentation itself, we can analyze that the capitalize function just takes the value through and does the treatment with the necessary methods to obtain the result, with no interference in the original value of the component’s state.</p><p>In some situations, the <strong>Filters</strong> can be very similar to the <strong>Computed Properties</strong>, with the difference that in the filters, the data is not transformed, they just change the output and return a version with the determined filtering of the information. Thus, a new value is not generated for that component data.</p><h3>Global Filters</h3><p>There are certain situations where a particular filter can be used on several components within your application, especially in those larger projects, where several interactions of the system can occur throughout the project.</p><p>For this, there is the possibility of creating global filters, and just as I said earlier, equally to mixins, plugins, among others, they are available anywhere in your project, facilitating their use and the reuse of codes.</p><pre>Vue.filter(&#39;capitalize&#39;, function (value) {<br>   if (!value) return &#39;&#39;<br>   value = value.toString()<br>   return value.charAt(0).toUpperCase() + value.slice(1)<br>})</pre><pre>new Vue({<br>   // your Vue instance...<br>})</pre><p>In this example, we see the creation of a global filter, using the .filter property inside the main.js. If your application uses many filters, for organization reasons, it is recommended to create a separate file and place all filters in them and import them into the main.js file. And there is a detail that is very important and should always be remembered: when a global filter has the same name as a local filter, the local filter will have priority.</p><p>Since filters are JavaScript functions, they accept the value to be transformed as the first parameter. You can also pass as many arguments as you need according to the needs of your application.</p><pre>{{ message | filterA(&#39;arg1&#39;, arg2) }}</pre><p>Just as we can pass several arguments, it is possible to link several filters, for that we just need to use the pipe symbol (|) and through several transforming filters, we obtain a single value.</p><pre>filters: {<br>    Upper(value) {<br>       return value.toUpperCase();<br>    },<br>        <br>    Lower(value) {<br>       return value.toLowerCase();<br>    },<br>}</pre><p>And within the value, we use it as follows:</p><pre>{{ message | Upper | Lower }}</pre><p>Of course, this example would have no functionality, but just to exemplify that it is possible to put several filters within a single value, and as I mentioned that they are chained, the Lower function will be executed after obtaining the result of Upper, being passed as the only one Lower’s argument.</p><p>Explore your knowledge and studies a little in this Vue.js feature that allows you to help with various tasks in your applications. See more in the <a href="https://vuejs.org/">official documentation</a>.</p><p>If you liked this article, be sure to share and comment. If you want to know a little more, exchange some ideas, you can leave your opinion on the subject in the comments and even suggest something for the next articles.</p><p>Enjoy and get to know a little of my work, visit the website <a href="http://www.fsenaweb.me/">www.fsenaweb.me</a>, it has my portfolio, my social networks (including <a href="https://github.com/fsenaweb/">GitHub</a>, where you have some sample applications to practice with Vue.js), and a small space for contacts.</p><p><a href="https://github.com/fsenaweb/">fsenaweb - Overview</a></p><p>And be sure to join our group and Vue.js in Brazil, through Telegram (<a href="https://t.me/vuejsbrasil">VueJS Brasil</a>), has a very special gallery ready to exchange other experiences.</p><p>That’s it, see you next time! My name is <em>Matheus Ricelly</em>, and for your attention, <em>my thanks</em>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72c24e492e6c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/js-dojo/knowing-and-developing-filters-in-vue-js-72c24e492e6c">Knowing and developing filters in Vue.js</a> was originally published in <a href="https://medium.com/js-dojo">Vue.js Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Conhecendo e desenvolvendo filtros no Vue.js]]></title>
            <link>https://fsenaweb.medium.com/conhecendo-e-desenvolvendo-filtros-no-vue-js-cc79f6b9ca70?source=rss-9f0709f6da2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc79f6b9ca70</guid>
            <category><![CDATA[components]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[filters]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Matheus Ricelly]]></dc:creator>
            <pubDate>Thu, 06 Feb 2020 12:52:25 GMT</pubDate>
            <atom:updated>2020-02-06T15:26:05.431Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*Xb8RD3_8I_uiX3749QhB5Q.png" /></figure><p>Olá pessoal!</p><p>Nesse artigo, de forma especial, irei falar sobre uma funcionalidade que na minha opinião é pouco utilizada (ou comentada) dentro da comunidade Vue.js, que são os <strong>Filtros</strong>. Assim como os Plugins, Diretivas Personalizadas e os <a href="https://medium.com/@fsenaweb/trabalhando-com-mixins-no-vue-js-df82c71d4aca">Mixins</a>, os filtros fazem parte das <em>funcionalidades reutilizáveis</em> dentro do Vue, auxiliando no processo de criação de componentes.</p><blockquote>Nos componentes do Vue, os filtros são funcionalidades que nos permitem obter diversas formatações na saída dos dados dinâmicos do seu estado. Ou seja, eles não alteram os dados de um componente, apenas podem formatar seus dados na renderização.</blockquote><h3>Filtros locais</h3><p>Conforme a <a href="https://vuejs.org/v2/guide/filters.html">documentação oficial</a>, a utilização dos filtros ocorrem dentro de interpolações mustache e expressões v-bind. Veja um exemplo da formatação do filtro no template:</p><pre>&lt;!-- em interpolações de texto --&gt; <br>{{ message | capitalize }}  </pre><pre>&lt;!-- em interligações de atributos --&gt; <br>&lt;div v-bind:text=&quot;message | capitalize&quot;&gt;&lt;/div&gt;</pre><p>Criando de forma local, dentro do componente, podemos ter:</p><pre>filters: {<br>   capitalize(value) {<br>     if (!value) return &#39;&#39;<br>     value = value.toString()<br>     return value.charAt(0).toUpperCase() + value.slice(1)<br>   }<br>}</pre><p>Nesse primeiro exemplo, extraído da própria documentação, podemos analisar que a função capitalize apenas pega o valor passar e faz o tratamento com os métodos necessários para que se obtenha o resultado, não existindo nenhuma interferência no valor original do estado do componente.</p><p>Em algumas situações, os <strong>Filtros</strong> podem ser bem semelhantes as <strong>Propriedades Computadas</strong>, com a diferença de que nos filtros, os dados não são transformados, eles apenas alteram a saída e retornam uma versão com o determinada filtragem da informação. Assim, não é gerado um novo valor para aquele dado do componente.</p><h3><strong>Filtros Globais</strong></h3><p>Tem certas situações onde determinado filtro poderá ser usado em diversos componentes dentro da sua aplicação, principalmente naqueles projetos maiores, onde pode ocorrer diversas interações do sistema ao longo do projeto.</p><p>Para isso, existe a possibilidade de se criar os filtros globais, e assim como disse anteriormente, igualmente aos mixins, plugins, entre outros, eles ficam disponíveis em qualquer parte do seu projeto, facilitando a sua utilização e o reaproveitamento dos códigos.</p><pre>Vue.filter(&#39;capitalize&#39;, function (value) {<br>   if (!value) return &#39;&#39;<br>   value = value.toString()<br>   return value.charAt(0).toUpperCase() + value.slice(1)<br>})</pre><pre>new Vue({<br>   // sua instância do Vue...<br>})</pre><p>Nesse exemplo vemos a criação de um filtro global, utilizando a propriedade .filter dentro do arquivo main.js. Caso sua aplicação utilize muitos filtros, por questão de organização, é recomendado criar um arquivo separado e colocar todos os filtros neles e fazer o <em>import</em> dentro do arquivo main.js. E tem um detalhe que é muito importante e deve sempre ser lembrado: quando um filtro global possuir o mesmo nome de um filtro local, o filtro local terá prioridade.</p><p>Como os filtros são funções JavaScript, eles aceitam o valor a ser transformado como o primeiro parâmetro. Você também pode passar quantos argumentos achar necessários de acordo com a necessidade da sua aplicação.</p><pre>{{ message | filterA(&#39;arg1&#39;, arg2) }}</pre><p>Assim como podemos passar diversos argumentos, é possível encadear diversos filtros, para isso basta utilizarmos o símbolo pipe (|) e através de diversos filtros transformadores, obtermos único valor.</p><pre>filters: {<br>    Upper(value) {<br>       return value.toUpperCase();<br>    },<br>        <br>    Lower(value) {<br>       return value.toLowerCase();<br>    },<br>}</pre><p>E dentro do valor, utilizamos da seguinte forma:</p><pre>{{ message | Upper | Lower }}</pre><p>Claro que esse exemplo não teria nenhuma funcionalidade, mas apenas para exemplificar que é possível colocarmos diversos filtros dentro de um único valor, e como eu mencionei que são encadeadas, a função <em>Lower</em> será executada após obter o resultado de <em>Upper</em>, sendo passado como o único argumento de <em>Lower</em>.</p><p>Explore um pouco os seus conhecimentos e estudos nessa funcionalidade do Vue.js que te permite ajudar em diversas tarefas nas suas aplicações. Veja mais na <a href="https://vuejs.org/">documentação oficial</a>.</p><p>Se você gostou desse artigo, não deixe de compartilhar e comentar. Se você quiser saber um pouco mais, trocar algumas idéias, poderá deixar nos comentários sua opinião sobre o assunto e até sugerir algo para os próximos artigos.</p><p>Aproveite e conheça um pouco dos meus trabalhos, visite o site <a href="https://fsenaweb.me/"><strong><em>www.fsenaweb.me</em></strong></a> , ele tem o meu portfólio, minhas redes sociais (inclusive o <a href="https://github.com/fsenaweb/">GitHub</a> , onde você tem a disposição algumas aplicações de exemplos para praticar com o Vue.js), e um pequeno espaço para contatos.</p><p><a href="https://github.com/fsenaweb">fsenaweb - Overview</a></p><p>E não deixe de participar de nosso grupo no Telegram ( <a href="https://t.me/vuejsbrasil"><strong>VueJS Brasil</strong></a> ), tem uma galeria muito especial pronta trocar outras experiências.</p><p>E é isso, até a próxima! Meu nome é <em>Matheus Ricelly</em> , e pela sua atenção, o meu <em>muito obrigado</em> !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc79f6b9ca70" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to work with mixins on Vue.js]]></title>
            <link>https://javascript.plainenglish.io/how-to-work-with-mixins-on-vue-js-a61f72737f25?source=rss-9f0709f6da2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a61f72737f25</guid>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Matheus Ricelly]]></dc:creator>
            <pubDate>Thu, 26 Sep 2019 08:59:17 GMT</pubDate>
            <atom:updated>2020-02-06T11:03:56.698Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*Kd7mrwqmrzyAudv8tS-OdQ.png" /></figure><p>Through my work with Vue, I have gained experience in developing components and reusing them in applications, thus gaining agility, time, resources, among others. And in recent projects I had come to realize that some of my components had very similar code, including some methods, computed properties.</p><p>It was a lot of code that I practically copied and pasted from one component to another, changing small details and that caught my attention, so I went to get more information on the internet, mainly in the documentation of Vue.js itself, and also in telegram, in the Vuejs Brasil group. I found out that there is a fantastic feature that is Mixins, where the documentation itself gives a clear explanation:</p><blockquote>Mixins are a flexible way to distribute reusable functionalities for Vue components. A mixin object can contain any component options. When a component uses a mixin, all options in the mixin will be “mixed” into the component’s own options.</blockquote><p>Clearer than that, impossible, isn’t it ?! Mixins allow you to have methods, props, data, computed properties applied to various components. They closely resemble an approach to having an inheritance composition (those same inheritances we find in C #, Java, and other languages). Well, after that, I saw that my work on code reuse has slowed down a lot, making it even faster to build my applications. But let’s stop talking and let’s practice.</p><h3>Let’s go to the example!</h3><p>Inside your Vue application, we will create a folder called mixins, where we will put files with extension .js to import in the components where we will take advantage of the codes in the application.</p><blockquote>In my case, I will use some words in the Portuguese language, but nothing is changed in the use of features.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1dJ50HokwxdxG_2FEwVvkw.png" /><figcaption>We call this file named nomeMixins.js</figcaption></figure><p>In this first example (nomeMixins.js) I created a constant named nomeMixins and returned an object, just as we do in the Vue instance itself containing three simple properties for our study. Now we can import the nomeMixins.js file into the component:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*4Qt1hLC-h7mTOY8OYBCiaQ.png" /><figcaption>Part of the .vue component with the nomeMixins import.</figcaption></figure><p>Initially we made the import (<em>import nomeMixins …</em>) and declared mixins and assigned the value declared in import, in this case being mixins: [nomeMixins], where you can insert several other files through an array.</p><p>Not only with the data() we can work with, as I said earlier, you can work with methods, computed properties, and many others. Continuing, in the same file nameMixins.js, we will insert a computed property, where it will join 2 properties of the object in data (), which follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HqXi0aVSXreueCTQx2k-mA.png" /></figure><p>In the .vue component, we don’t need to add anything, since it already understands that that computed property will be part of it, so just call it inside the &lt;template&gt; &lt;/template&gt; tag or via a console.log () to view the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*ZOvufRYZ62MKSJF07aEPtA.png" /></figure><p>This saves you line after line of code for activities that are repetitive on your site or application with Vue.js. There are several possibilities for this reuse, including a way to produce a <strong>global mixin</strong> where you can use it in all instances of Vue, but the documentation itself recommends caution, as this may affect other parts of your code.</p><p>You can find more information in the <a href="https://vuejs.org/">official Vue.js documentation</a>, containing many examples of using mixins in your application, go there and check it out.</p><p>If you enjoyed this article, be sure to share and comment. If you want to know a little more, exchange some ideas (I’m still improving my English, but we can talk), you can leave your comments on the subject and even suggest something for the next articles.</p><p>Enjoy and know a little of my work, visit the site <a href="http://www.fsenaweb.me/"><strong>www.fsenaweb.me</strong></a>, he has my portfolio, my social networks (including <a href="https://github.com/fsenaweb/">GitHub</a>, where you have available some sample applications to practice with Vue.js), and a small space for contacts.</p><p><a href="https://github.com/fsenaweb/">fsenaweb - Overview</a></p><p>And that’s it, see you next time! My name is Matheus Ricelly, and for your attention, thank you very much!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a61f72737f25" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-to-work-with-mixins-on-vue-js-a61f72737f25">How to work with mixins on Vue.js</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Your Application with Styled Components in Vue.js]]></title>
            <link>https://javascript.plainenglish.io/building-your-application-with-styled-components-in-vue-js-8d0fdd8e605a?source=rss-9f0709f6da2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d0fdd8e605a</guid>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[styled-components]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[Matheus Ricelly]]></dc:creator>
            <pubDate>Mon, 02 Sep 2019 14:27:51 GMT</pubDate>
            <atom:updated>2021-06-25T17:33:05.722Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8f3K44-HlT8zso81yBV-dQ.jpeg" /></figure><p>Hi everybody!</p><blockquote>The original article is <a href="https://medium.com/@fsenaweb/construindo-sua-aplicacao-com-styled-components-no-vue-js-3e550449ae0e"><strong>here</strong></a>.</blockquote><p>For those unfamiliar, Styled-Components is a very popular library within the React and React Native community, where it provides developers with the ability to create their CSS code within JavaScript.</p><p>Developers with Vue know how easy it is to work with component styling, using CSS along with HTML and JavaScript in a single file; and all this thanks to the power of SFC (Single File Components). This was undoubtedly a very positive point and it helped boost Vue’s popularity in the Front End community.</p><p>However, in recent months, I have been using React in the development of a large project, and it was from there, that I knew this library and have used it in the stylization part of it; I even confess that I made the application much more organized and practical. At first it’s kind of confusing, but then you start to like this library a lot.</p><p>But like most of my projects I use Vue, so I decided to research a way to unite the practicality of the Style-Components library with the power of Vue.js and its ecosystem. It was then that I discovered that there is a specific library for Vue, maintained by the same creators of React’s styled-components, which is called <a href="https://github.com/styled-components/vue-styled-components"><strong>vue-styled-components</strong></a>.</p><p><a href="https://github.com/styled-components/vue-styled-components">styled-components/vue-styled-components</a></p><p>And if you have projects in React and want to make the switch to Vue (yes, the change process is happening in that direction too and it has increased a lot), with styles created with styled-components, they can be easily migrated, thus earning, agility, performance and scalability.</p><h3>Get started</h3><p>But let’s put the conversation aside and let’s go to the code! The process of installing and using vue-styled-components is very simple and practical. With your project created, just install the library using your preferred package manager (Yarn, NPM).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J8dbCu7rXWDes-l8icEEkg.png" /><figcaption>Library installation step</figcaption></figure><p>It’s not complicated at all, and you can quickly use the potential of this library in your application. In my GitHub I left a project with examples of stylized tags and some ways to interact with them using vue-styled-components.</p><p>Each element/tag used in the examples can be treated by vue-styled-components as an isolated Component with its individual properties, or by receiving data from other components.</p><p>In our first example, as introductory and basic as possible, let’s create a button with a default style. Don’t worry right now, customizing these tags, we are slowly evolving into a process where this component can be mapped and allow for dynamic style updates.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5495d817cac514b16f34acdfef398b8/href">https://medium.com/media/a5495d817cac514b16f34acdfef398b8/href</a></iframe><p>After creating the Button.js file, just use it as you would import any component into Vue and give the file a name for the tag within the HTML code in SFC (<em>I will consider here that you are already familiar with using it). from Vue.js and all of its architecture</em>).</p><p>I usually use the letter C as a prefix (which refers to the word Component), to name the custom tags I use in Vue; It’s a good practice I learned from Angular. At this point, anywhere in our application, we can use this stylized component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/056106c92f531641c95ad6f97b1d26a6/href">https://medium.com/media/056106c92f531641c95ad6f97b1d26a6/href</a></iframe><h4>Passing properties</h4><p>In vue-styled-components you can dynamically define styles for a component by passing these values through properties. We will refine our Button component by making it possible to modify the button style according to the parameters passed. In this example we are informing that when the primary attribute is passed, the button will receive a new background style and font color.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ffb88eceec8bec1a7b2dbf5d3fd0e42/href">https://medium.com/media/1ffb88eceec8bec1a7b2dbf5d3fd0e42/href</a></iframe><p>There is no secret in this code, simply, we just made a ternary informing if there is the primary attribute it returns one color, if not, will return another. The above example can be improved and even added new properties (you can pass as many attributes as you like); Everything goes according to your need within the project.</p><h4>Enhancing the properties</h4><p>Manipulating the properties we receive gives us a chance to get diverse components in a single file, placing conditions that satisfy certain styles. In the example below, you have the opportunity to choose which color scheme you want to assign to your button without affecting the others, thus diversifying your application.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d913a32c5eaa5d54fa573a1acfb0eb6d/href">https://medium.com/media/d913a32c5eaa5d54fa573a1acfb0eb6d/href</a></iframe><p>To better explain the process of creating this button: we start (always) calling <em>vue-styled-components</em>, right after (<em>from line 3 to line 6</em>), we need to define which types of properties will be passed to the component, in which case we create two types. , which are type and radius; This second property is just to show if we want a button with rounded edges or not.</p><p>From <em>line 8 to 31</em>, we create a function, which takes the value of the type property and makes a conditional (in this case we use the switch) and see the value entered, according to what was passed, it returns the background attributes. color and color of their respective case, if nothing is passed as property, then the button will be given a default value.</p><p>From this knowledge, you can implement new attributes such as <em>font size, padding, margin</em>, among other attributes that can make your custom component very dynamic and being used throughout the application.</p><p>I left these little examples in my GitHub so you can take the initial step to implement this library. Enjoy and submit new stylized fields to help other friends who also want to learn.</p><p><a href="https://github.com/fsenaweb/vue-styled-components?source=post_page-----3e550449ae0e----------------------">fsenaweb/vue-styled-components</a></p><p>If you enjoyed this article, be sure to share and comment. If you want to know a little more, exchange some ideas (I’m still improving my English, but we can talk), you can leave your comments on the subject and even suggest something for the next articles.</p><p>Enjoy and know a little of my work, visit the site <a href="http://www.fsenaweb.me/"><strong>www.fsenaweb.me</strong></a>, he has my portfolio, my social networks (including <a href="https://github.com/fsenaweb/">GitHub</a>, where you have available some sample applications to practice with Vue.js), and a small space for contacts.</p><p><a href="https://github.com/fsenaweb">fsenaweb - Overview</a></p><p>And that’s it, see you next time! My name is Matheus Ricelly, and for your attention, thank you very much!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d0fdd8e605a" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/building-your-application-with-styled-components-in-vue-js-8d0fdd8e605a">Building Your Application with Styled Components in Vue.js</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Construindo sua aplicação com Styled Components no Vue.js]]></title>
            <link>https://fsenaweb.medium.com/construindo-sua-aplica%C3%A7%C3%A3o-com-styled-components-no-vue-js-3e550449ae0e?source=rss-9f0709f6da2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e550449ae0e</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[components]]></category>
            <category><![CDATA[styled-components]]></category>
            <dc:creator><![CDATA[Matheus Ricelly]]></dc:creator>
            <pubDate>Thu, 29 Aug 2019 13:53:15 GMT</pubDate>
            <atom:updated>2019-08-29T13:53:15.898Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V8B2hh70R6GLsy7khGBJ2w.jpeg" /></figure><p>Olá pessoal, estou de volta!</p><p>Para quem não conhece, o Styled-Components é uma biblioteca muito popular dentro da comunidade React e do React Native, onde ela proporciona ao desenvolvedor criar seus códigos CSS dentro do JavaScript.</p><p>Quem desenvolve com Vue sabe a facilidade que é trabalhar com a estilização dos componentes, utilizando o CSS juntamente com o HTML e o JavaScript num único arquivo; e tudo isso graças ao poder do SFC (Single File Components). Esse foi sem dúvida, um ponto muito positivo e que ajudou a impulsionar a popularidade do Vue na comunidade Front-end.</p><p>Porém, nos últimos meses, tenho utilizado o React no desenvolvimento de um projeto de grande porte, e foi a partir daí, que conheci essa biblioteca e tenho utilizado na parte da estilização do mesmo; e até confesso que deixei a aplicação muito mais organizada e prática. No início é até meio confuso, mas depois você começa a gostar muito dessa biblioteca.</p><p>Mas como a maior parte dos meus projetos eu utilizo o Vue, então decidi pesquisar uma forma de unir a praticidade da biblioteca Style-Components com o poder do Vue.js e seu ecossistema. Foi então então que descobri que existe uma biblioteca específica pra o Vue, mantida pelos mesmos criadores do styled-components do React, e que se chama <a href="https://github.com/styled-components/vue-styled-components"><strong>vue-styled-components</strong></a><strong>.</strong></p><p><a href="https://github.com/styled-components/vue-styled-components">styled-components/vue-styled-components</a></p><p>E caso você tenha projetos no React e queira fazer a mudança para o Vue (sim, o processo de mudança também ocorre nesse sentido e tem aumentado muito), com os estilos criados com o styled-components, podem ser facilmente migrados, ganhando assim, agilidade, performance e escalabilidade.</p><h3>Primeiros Passos</h3><p>Mas vamos deixar a conversa de lado e vamos ao código! O processo de instalação e utilização do vue-styled-components é bem simples e prático. Já com o seu projeto criado, basta apenas instalar a biblioteca utilizando seu gerenciador de pacotes preferido (Yarn, NPM).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W7RBObyMNUNkK6PrlkY1tg.png" /><figcaption>Etapa de instalação da biblioteca</figcaption></figure><p>Não é nada complicado, e rapidamente você poderá utilizar o potencial dessa biblioteca na sua aplicação. No meu <a href="https://github.com/fsenaweb/"><strong>GitHub</strong></a> eu deixei um projeto com exemplos de tags estilizadas e algumas formas de interagir com elas utilizando o vue-styled-components.</p><p>Cada elemento/tag utilizado nos exemplos podem ser tratadas pelo vue-styled-components como um Componente isolado e com suas propriedades individuais, ou recebendo dados de outros componentes.</p><p>No nosso primeiro exemplo, de forma mais introdutória e básica possível, vamos criar um botão com um estilo padrão. Não se preocupe nesse momento, em personalizar essas tags, vamos aos poucos evoluindo até um processo em que esse componente poderá ser mapeado e permitir atualizações de estilo de forma dinâmica.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5495d817cac514b16f34acdfef398b8/href">https://medium.com/media/a5495d817cac514b16f34acdfef398b8/href</a></iframe><p>Após criar o arquivo Button.js, basta ser utilizado da mesma forma que estaria importando qualquer componente dentro do Vue e atribuindo ao arquivo um nome para a tag dentro do código HTML no SFC (<em>Vou considerar aqui, que você já tem familiaridade com o uso do Vue.js e toda a sua arquitetura</em>).</p><p>Eu costumo utilizar a letra C como um prefixo (que remete a palavra Componente), para atribuir os nomes as tags personalizadas que utilizo no Vue; é uma boa prática que aprendi com o Angular. Nesse instante, em qualquer lugar em nosso aplicativo, poderemos utilizar esse componente estilizado.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/056106c92f531641c95ad6f97b1d26a6/href">https://medium.com/media/056106c92f531641c95ad6f97b1d26a6/href</a></iframe><h4>Passando propriedades</h4><p>No vue-styled-components você pode definir estilos a um componente de forma dinâmica, passando esses valores através de propriedades. Vamos aperfeiçoar o nosso componente Button, colocando a possibilidade de modificar o estilo de botão, de acordo com os parâmetros passados. Nesse exemplo estamos informando que ao ser passado o atributo <strong><em>primary</em></strong>, o botão irá receber um novo estilo de background e cor da fonte.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ffb88eceec8bec1a7b2dbf5d3fd0e42/href">https://medium.com/media/1ffb88eceec8bec1a7b2dbf5d3fd0e42/href</a></iframe><p>Não há segredo nesse código, de forma simples, apenas fizemos um ternário informando caso existe o atributo primary ele retorna uma cor, caso não exista, retornará outra. O exemplo acima pode ser melhorado e até acrescentada novas propriedades (é possível passar quantos atributos quiser); tudo vai de acordo com a sua necessidade dentro do projeto.</p><h4>Aprimorando as propriedades</h4><p>Manipular as propriedades recebidas nos dá uma chance de obter componentes diversificados em um único arquivo, colocando condições que satisfaçam a determinados estilos. No exemplo abaixo, você tem a oportunidade de escolher qual o esquema de cores deseja atribuir ao seu botão, sem que isso afete aos demais, diversificando assim sua aplicação.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d913a32c5eaa5d54fa573a1acfb0eb6d/href">https://medium.com/media/d913a32c5eaa5d54fa573a1acfb0eb6d/href</a></iframe><p>Explicando melhor o processo de criação desse botão: iniciamos (sempre) chamando o <em>vue-styled-components</em>, logo após (<em>da linha 3 a linha 6</em>), precisamos definir qual os tipos de propriedades que serão passadas ao componente, nesse caso criamos dois tipos, que são <em>type e radius</em>; essa segunda propriedade é apenas para mostrarmos se vamos querer um botão com bordas arredondadas ou não.</p><p>Da <em>linha 8 até a 31</em>, criamos uma função, que pega o valor da propriedade type e faz uma condicional (nesse caso utilizamos o switch) e ver o valor informado, de acordo com o que foi passado, ele retorna os atributos de <em>background-color</em> e <em>color </em>dos seus respectivos case, caso nada seja passado como propriedade, então o botão receberá um valor padrão.</p><p>A partir desse conhecimento, você poderá implementar novos atributos, como <em>tamanho da fonte, padding, margin</em>, entre outros atributos que poderão deixar seu componente personalizado de forma bem dinâmica e sendo utilizada em toda a aplicação.</p><p>Deixei esses pequenos exemplos no meu GitHub para que você possa dá o passo inicial para implementar essa biblioteca. Aproveite e envie novos campos estilizados para ajudar aos demais amigos que também desejam aprender</p><p><a href="https://github.com/fsenaweb/vue-styled-components">fsenaweb/vue-styled-components</a></p><p>Se você gostou desse artigo, não deixe de compartilhar e comentar. Se você quiser saber um pouco mais, trocar algumas idéias, poderá deixar nos comentários sua opinião sobre o assunto e até sugerir algo para os próximos artigos.</p><p>Aproveite e conheça um pouco dos meus trabalhos, visite o site <a href="https://fsenaweb.me/"><strong><em>www.fsenaweb.me</em></strong></a> , ele tem o meu portfólio, minhas redes sociais (inclusive o <a href="https://github.com/fsenaweb/">GitHub</a> , onde você tem a disposição algumas aplicações de exemplos para praticar com o Vue.js), e um pequeno espaço para contatos.</p><p><a href="https://github.com/fsenaweb">fsenaweb - Overview</a></p><p>E não deixe de participar de nosso grupo no Telegram ( <a href="https://t.me/vuejsbrasil"><strong>VueJS Brasil</strong></a> ), tem uma galeria muito especial pronta trocar outras experiências.</p><p>E é isso, até a próxima! Meu nome é <em>Matheus Ricelly</em> , e pela sua atenção, o meu <em>muito obrigado</em> !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e550449ae0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Trabalhando com Mixins no Vue.js]]></title>
            <link>https://fsenaweb.medium.com/trabalhando-com-mixins-no-vue-js-df82c71d4aca?source=rss-9f0709f6da2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/df82c71d4aca</guid>
            <category><![CDATA[components]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[mixin]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[Matheus Ricelly]]></dc:creator>
            <pubDate>Sun, 24 Mar 2019 00:37:39 GMT</pubDate>
            <atom:updated>2019-03-24T01:25:22.619Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*mGLyzR9e51d_DEYWyQ1Hog.jpeg" /></figure><p>Fala galera! Após um longo tempo sem escrever, estou de volta trazendo mais conteúdo sobre a área de desenvolvimento web. No meu último artigo, eu escrevi sobre o futuro do CodeIgniter, sobre o que está por vir na versão 4 daquele framework.</p><p>Enquanto a nova versão do CI não sai, eu estou desenvolvendo meus projetos com outros frameworks, entre eles, o Laravel. E sem me estender muito na história, eu acabei conhecendo o Vue.js, essa fantástica ferramenta para o desenvolvimento front-end com javascript.</p><p>Dentro dos meus trabalhos com Vue, eu venho adquirindo experiência no desenvolvimento de componentes e reaproveitamento dos mesmos nas aplicações, ganhando assim, agilidade, tempo, recursos, entre outros. E nos últimos projetos eu vinha percebendo que alguns dos meus componentes tinham códigos bastante semelhantes, entre os quais, alguns methods, computed properties.</p><p>Era muito código que eu praticamente copiava e colava de um componente para outro, mudando pequenos detalhes e isso me chamou a atenção, ai fui buscar mais informações na internet, principalmente na documentação do próprio <a href="https://br.vuejs.org/">Vue.js</a>, e também no telegram, no grupo Vuejs Brasil. Acabei descobrindo que existe uma funcionalidade fantástica que são os Mixins , onde a própria documentação dá uma clara explicação:</p><blockquote>Mixins são uma forma flexível de distribuir funcionalidade reutilizável em diversos componentes Vue. Um objeto <em>mixin</em> pode conter quaisquer opções de componente. Quando um componente utiliza um <em>mixin</em>, todas as opções deste serão misturadas (em inglês, <em>mixed in</em>) com as opções do próprio componente.</blockquote><p>Mais claro que isso, impossível, não é?! Os Mixins permitem que você tenha métodos, props, dados, propriedades computadas aplicados a vários componentes. Eles lembram bem uma abordagem para termos uma <em>composição sobre herança (aquelas mesmas heranças que encontramos no C#, Java e outras linguagens). </em>Pois bem, depois disso, vi que o meu trabalho com a reutilização de códigos diminuiu muito, agilizando ainda mais na criação dos meus aplicativos. Mas vamos deixar de conversas e vamos praticar.</p><h3><strong>Vamos ao exemplo</strong></h3><p>Dentro da sua aplicação no Vue, vamos criar um pasta chamada <strong>mixins</strong>, nela colocaremos aquivos com extensão .js para importamos nos componentes onde iremos aproveitar os códigos na aplicação.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1dJ50HokwxdxG_2FEwVvkw.png" /><figcaption>Chamamos esse arquivo com o nome nomeMixins.js</figcaption></figure><p>Nesse primeiro exemplo (nomeMixins.js) criei uma constante chamada nomeMixins e nela retornei um objeto, igual fazemos na própria instância do Vue contendo três simples propriedades para o nosso estudo. Agora podemos importar o arquivo nomeMixins.js dentro do componente:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*4Qt1hLC-h7mTOY8OYBCiaQ.png" /><figcaption>Parte do componente .vue com o import do nomeMixins.</figcaption></figure><p>Inicialmente fizemos a importação (<em>import nomeMixins … </em>) e declaramos o mixins e atribuimos o valor declarado no import, no caso ficando como <strong><em>mixins: [nomeMixins]</em></strong>, onde você pode inserir diversos outros arquivos através de um array.</p><p>Não só com o data() que podemos trabalhar, como falei anteriormente, você pode trabalhar com métodos, propriedades computadas, e muitas outras. Dando continuidade, no mesmo arquivo nomeMixins.js, vamos inserir uma propriedade computada, onde ela unirá 2 propriedades do objeto em data(), que segue:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HqXi0aVSXreueCTQx2k-mA.png" /></figure><p>No componente .vue, não precisaremos acrescentar nada, pois ele já entende que aquela propriedade computada fará parte dele, dessa forma, basta apenas você chamá-lo dentro da tag &lt;template&gt;&lt;/template&gt; ou através de um console.log() para visualizar o resultado:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*ZOvufRYZ62MKSJF07aEPtA.png" /></figure><p>Dessa forma, você economiza linha e mais linhas de códigos para atividades que são repetitivas no seu site ou aplicativo com Vue.js. Existem diversas possibilidades desse reaproveitamento, inclusive há uma forma de se produzir um <strong><em>mixin global</em></strong>, onde você poderá utilizá-lo em todas as instâncias do Vue, mas a própria documentação recomenda ter cuidado, pois isso pode afetar outras partes dos seus códigos.</p><p>Você pode encontrar mais informações na <a href="https://br.vuejs.org/v2/guide/mixins.html">documentação oficial do Vue.js</a> (totalmente em português), contendo muitos exemplos da utilização dos mixins na sua aplicação, acesse lá e confere. E não deixe de participar no nosso grupo no Telegram (<a href="https://t.me/vuejsbrasil"><strong>VueJS Brasil</strong></a>), tem uma galera muito especial pronta trocar umas experiências.</p><p>Em breve trarei mais assuntos para compartilhar com a comunidade. Não só sobre Vue ou CodeIgniter, mas irei escrever algumas das minhas experiências com diversas tecnologias, entre elas o Docker, React, Laravel e até com os microframeworks.</p><p>Se você gostou desse artigo, não deixe de compartilhar e comentar. Se quiser saber um pouco mais, trocar umas ideias, você pode deixar nos comentários a sua opinião sobre o assunto, e até sugerir algo para os próximos artigos.</p><p>Aproveite e conheça um pouco dos meus trabalhos, visitando o site <a href="https://fsenaweb.me/"><strong><em>www.fsenaweb.me</em></strong></a>, lá tem o meu portfólio, minhas redes sociais (inclusive o meu <a href="https://github.com/fsenaweb/">GitHub</a>, onde disponibilizo algumas aplicações exemplos para praticarem com Vue.js), tem ainda espaço para contatos e até artigos que eu publico e compartilho de outros colegas programadores, como forma de difundir conhecimentos.</p><p>E é isso, até a próxima! Meu nome é <em>Matheus Ricelly</em>, e pela sua atenção, o meu <em>muito obrigado</em>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df82c71d4aca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[O que esperar do CodeIgniter para o futuro ?]]></title>
            <link>https://fsenaweb.medium.com/o-que-esperar-do-codeigniter-para-o-futuro-a04971e45f25?source=rss-9f0709f6da2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a04971e45f25</guid>
            <category><![CDATA[framework]]></category>
            <category><![CDATA[codeigniter]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[mvc-frameworks]]></category>
            <dc:creator><![CDATA[Matheus Ricelly]]></dc:creator>
            <pubDate>Fri, 17 Nov 2017 01:55:59 GMT</pubDate>
            <atom:updated>2017-11-24T19:40:54.286Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mdvbGnlXGkVbdyQskRKvcw.png" /></figure><p>É bem verdade que há tempos o CodeIgniter tem caminhado a passos muito mais lentos em comparação aos demais frameworks existentes no mercado. Diversos fatores contribuíram para que isso acontecesse, e talvez, o mais impactante, tenha sido a saída da EllisLab, em outubro de 2014, da manutenção do projeto.</p><p>Isso trouxe muitas incertezas aos seus usuários. Muito se questionava quanto a EllisLab deixar o projeto morrer, ou se ela abriria o projeto para que a própria comunidade comandasse ou se teria alguma empresa/instituição que trouxesse para si a responsabilidade de continuar o legado desse framework.</p><p>Não estou aqui querendo defender o CodeIgniter, muito menos tentar convencer que é melhor ou pior que qualquer outra ferramenta de desenvolvimento de aplicações em PHP, mas, ninguém pode negar que, mesmo diante das dificuldades, ainda continua sendo um framework bastante utilizado, principalmente por aqueles que estão iniciando nesse mundo dos padrões MVC (Model-View-Controller).</p><h3><strong>O tempo é o inimigo</strong></h3><p>A primeira versão do CodeIgniter (CI) surgiu em 28 de fevereiro de 2006 e desde o início já enfrentava certas dificuldades de aceitação com alguns usuários. O principal motivo era a integração do PHP5, onde existia muita resistência daqueles que ainda estavam se familiarizando com essa nova versão da linguagem.</p><p>O CI veio ser um “refúgio” à esses usuários que ainda relutavam em utilizar as novas features do PHP, na sua versão 5. Ainda existia uma forte influência da versão 4 e só em 2011, ou seja, 5 anos depois, com a versão 2.0 do framework, é que finalmente eles retiraram todo o suporte a versão 4.x e deram início com a versão 5.1.6 do PHP.</p><blockquote>Esse problema de versão, talvez tenha sido a pedra no sapato que distanciou os usuários do CodeIgniter, pois, enquanto outros frameworks estavam evoluindo juntamente com a linguagem, o CI ficou preso a um grupo de usuários que preferiram manter-se presos ao problemático PHP4.</blockquote><h3><strong>Respirando por aparelhos</strong></h3><p>Mas o Codeigniter provou que ainda merece o seu lugar à sombra! Com a chegada da BCIT (<em>British Columbia Institute of Technology</em>), o projeto pôde então ser continuado, pois foi em substituição a EllisLab, esse novo fôlego foi tomado e a esperança que o CI retomaria e conquistaria o mercado.</p><p>A versão 3 trouxe novos ares e a aquela sensação que tudo poderia mudar, porém, não foi bem assim que as coisas caminharam. Muitas falhas persistiram, entre eles, o descompasso com o PHP, já em sua versão 7, continuou se tornando uma grande resistência para que o framework voltasse a ter o porte de uma ferramenta robusta.</p><p>As cartas estão lançadas para a versão 4, que, muitos acreditam, trará uma nova tentativa de trazer o CodeIgniter a um patamar superior dentro dos demais frameworks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KkUjgV1qclWqtOT8D-NjBw.png" /><figcaption>Na página oficial do CodeIgniter você já pode encontrar o link para o repositório da versão 4.x</figcaption></figure><h3><strong>A luta ainda continua</strong></h3><p>Eu, particularmente, ainda utilizo o CodeIgniter (atualmente utilizo outros frameworks, como Laravel, Symfony e o Silex) para pequenos projetos em PHP. Pequenos sistemas, um simples blog ou um CRUD básico, o CI ainda é muito eficiente e rápido nesse sentido.</p><p>Ao passo em que você precisa evoluir em suas aplicações, ele começa a ficar para trás. Um exemplo claro que passei recentemente foi a criação de uma API Rest, onde tentei ainda fazer algo no CI, porém, tive muitas dificuldades, passando horas e horas arrumando aquele “jeitinho” pra que ele funcionasse; foi quando decidi fazer com o Silex e em menos de uma hora estava com a API totalmente pronta e funcional.</p><p>E mesmo com todas essas dificuldades, atrasos em seu desenvolvimento, ele ainda continua sendo bastante procurado por programadores (acredito eu, os mais iniciantes) como ferramenta principal de desenvolvimento, como mostra a tabela a seguir:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Cz0x3iEVAB4rrA_d7q2gg.jpeg" /><figcaption>Um pequeno comparativo entre o CodeIgniter e os principais frameworks do mercado registrado pelo Google Trends.</figcaption></figure><p>Analisando o quadro, percebemos a grande ascensão do Framework Laravel,<strong> </strong>como também,<strong> </strong>vemos o Zend Framework em decadência (diversos fatores podem ser elencados, mas o principal seria a curva de aprendizagem que é muito alta) deixando ele para trás dos demais listados.</p><p>Mas, o principal objetivo desse quadro comparativo, é para mostrar que o Codeigniter ainda está em evidência, que continua sendo, mesmo com todos os seus problemas, uma opção muito viável para se utilizar. E novamente bato na mesma tecla: todo esse comparativo depende muito do tipo de aplicação que será desenvolvida por qualquer dos frameworks listados.</p><h3><strong>E a aprendizagem continua…</strong></h3><p>Mesmo estando um pouco afastado do framework CodeIgniter, porém, trabalhei por quase 4 anos com ele, pretendo fazer uma série de artigos, ensinando como desenvolver com essa ferramenta.</p><p>Serão artigos para usuários iniciantes, ensinando, desde a sua instalação, até a criação de um simples painel de controles de um “sisteminha” de blog, com o CRUD completo.</p><p>Espero poder compartilhar um pouco do meu conhecimento e ajudar cada vez mais a comunidade PHP no crescimento dessa linguagem.</p><p>Meu nome é <em>Matheus Ricelly</em>, e pela sua atenção, o meu <em>muito obrigado</em>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a04971e45f25" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>