Vue.js Digest 🇷🇺 🇺🇸
39 subscribers
389 photos
745 links
Дайджест новостей из мира vuejs
Download Telegram
SEO Analyzer — библиотека для поиска SEO дефектов

https://habr.com/ru/post/586728/?utm_campaign=586728&utm_source=habrahabr&utm_medium=rss
Всем привет!Сегодня хотел бы рассказать об одном решении самой частой проблемы в командной разработке, которое в итоге вылилось в целый npm пакет.И как вы поняли, речь пойдёт о SEO анализаторе, инструменте, который поможет отлавливать SEO дефекты на разных стадиях разработки (и, конечно же, сохранить хорошие отношения с SEO специалистами 😊). Читать далее
[Перевод] Стилизация однофайловых Vue компонентов

https://habr.com/ru/post/587604/?utm_campaign=587604&utm_source=habrahabr&utm_medium=rss
Если у вас есть опыт написания однофайловых Vue компонентов, вы, вероятно, сталкивались с написанием CSS в своем компоненте. Они позволяют разработчикам группировать код более логическими способами, а не разбивать компоненты по используемому языку (HTML, CSS или JavaScript). Возможность группировать стили компонентов непосредственно рядом с HTML-кодом, к которому он применяется, является одним из основных преимуществ Vue, включая возможность применять CSS к компоненту, чтобы он не влиял на другие части пользовательского интерфейса.Однако есть ряд функций взаимодействия Vue с CSS, с которыми вы, возможно, не знакомы, например, применение стилей непосредственно к элементам со слотами или новейшие функции, доступные в Vue 3.2. Давайте рассмотрим некоторые из этих других способов стилизации однофайловых Vue компонентов и их преимущества для ваших приложений. Читать далее
Какой JS-фреймворк выбрать новичку — мнения шести экспертов

https://habr.com/ru/post/587204/?utm_campaign=587204&utm_source=habrahabr&utm_medium=rss
Привет! Меня зовут Дима Чудинов, я наставник на веб-факультете Яндекс.Практикума, Head of Frontend в СберМаркете.



В первой статье о JS-фреймворках я рассказал о самых популярных из них: Angular, React, Vue и других. В комментариях опытные разработчики спорили о том, какой фреймворк лучше, а новички спросили у меня, какой же инструмент выбрать для проекта и с чего начать знакомство с библиотеками.







Большую часть пути разработчика я писал на React. Хоть я и начинал с AngularJS, но убеждён, что это не единственный путь и можно начать с любого другого фреймворка, поэтому для статьи я решил собрать мнения знакомых разработчиков, которые пишут на разных фреймворках. Статья не даст однозначного ответа на вопрос «Что же выбрать?», но поможет решить, в каком направлении двигаться. А ещё подскажет, какие инструменты лучше применять в пет-проектах, а какие — в энтерпрайзе. Если нет времени читать статью целиком, в конце я собрал список лучших фреймворков для новичков на основе личных мнений экспертов.
Читать дальше →
Как устроены мобильные номера. Давайте разберемся

https://habr.com/ru/post/587872/?utm_campaign=587872&utm_source=habrahabr&utm_medium=rss
Привет всем. Последнее время я писал код полей ввода input для номеров телефона и др. И мне пришлось углубиться в эту тему и разобраться как устроены мобильные номера телефонов. И в этой статье я хочу с вами поделиться своим опытом. Я постараюсь очень кратко, так что присоединяйтесь, потратьте 15 минут, если вы этого не знаете и вам любопытно.Если вы занимаетесь программированием на vue.js, то вот вам ссылка на компонент, который включает различные input поля в том числе для номеров телефонов. Мне кажется данный компонент может сильно облегчить вам жизнь, ниже ссылка на github и гифка как работает одно из полей. На этом по вступлению все, дальше только по теме.https://github.com/fakt309/inputv ЧИТАТЬ
Улучшаем производительность vue с помощью selective-object-reuse

https://habr.com/ru/post/587946/?utm_campaign=587946&utm_source=habrahabr&utm_medium=rss
Одна из причин тормозов vue приложения - излишний рендеринг компонентов. Разбираемся, с чем это обычно связано в vue2 и vue3, а затем применяем одну простую технику, которая лечит все эти случаи и не только их. Данная техника уже пол года хорошо работает в продакшене.Примеры этой статьи собраны в двух репозиториях (один для vue2, другой для vue3), с идентичным исходным кодом. Читать далее
Запрещаем браузеру Google Chrome сохранять и предлагать сохраненный пароль в нашем приложении на Vue.js(v2)

https://habr.com/ru/post/589481/?utm_campaign=589481&utm_source=habrahabr&utm_medium=rss
Мир стоит вверх ногами. Корпорация добра печется о нашей безопасности. И в то же время делает все, чтобы наши секреты стали достоянием гласности. Это я о политике гугл в плане сохранения логин-паролей в браузере, через него в аккаунте и о доступности всего нашего секретного добра всем, кто сможет подойти к нашим компьютерам.Да, удобно. Но небезопасно. И временами очень вредно. Запустил я очередной проект на работе. И самой большой проблемой по опыту старого проекта было то, что сотрудники вовсю пользовались автосохраненим паролей, поэтому под Васей мог сидеть Сергей и ни о какой нормальной аутентификации, а тем более разраничении прав доступа речи идти не могло. Читать далее
Управление данными в системе автоматизации на Vue и Vuex и решение проблем тестирования с помощью Jest

https://habr.com/ru/post/590753/?utm_campaign=590753&utm_source=habrahabr&utm_medium=rss
Привет! Меня зовут Артём Карачёв, я фронтенд-разработчик в Sportmaster Lab. Сейчас мы пишем модуль автоматизации физической фотостудии, где работают несколько фотографов, менеджеров, фоторедакторов, кладовщиков и других. Все фото кроссовок, которые вы видите в интернет-магазинах Спортмастера, снимают и загружают в базу данных именно эти люди. Благодаря модулю автоматизации они смогут их выгружать быстрее и легче. Возможно, наш опыт организации vuex-хранилища и слоя получения данных, а также последующего интеграционно-компонентного тестирования окажется кому-то полезным. Читать далее
Как мы ускоряли комментарии Хабра

https://habr.com/ru/post/590111/?utm_campaign=590111&utm_source=habrahabr&utm_medium=rss
Комментарии на Хабре иногда несут больше пользы, чем сама статья. Поэтому при переходе на новую версию сайта было важно сделать работу с комментами не хуже, чем было.



Вы когда-нибудь открывали в старом дизайне Хабра пост с большим числом комментариев? Страничка даже с тысячей сообщений грузится шустро, на ней без серьёзных задержек работает форма для ответа, кнопки голосования и закладок. Но когда мы начали переход на новую версию Хабра, стало понятно, что добиться такой же скорости будет непросто.



Этому есть несколько причин. Во-первых, Хабр стал одностраничным приложением (SPA, Single Page Application) на Vue, то есть теперь переходы между страницами рисуются на клиенте с помощью JS вместо классического серверного рендеринга (Server-Side Rendering, SSR). Такие SPA-страницы отображаются быстрее на современных устройствах, но на старых девайсах могут тормозить.



Во-вторых, движок старого Хабра — это больше десяти лет оптимизаций, костылей и заплаток. Вполне естественно, что если попытаться переписать их с нуля на современных технологиях, придётся учесть эту историю поиска и устранения бутылочных горлышек в производительности.



В октябре мы постепенно выкатывали на часть пользователей обновлённую версию комментариев, над которой трудились последние полгода. Наши новые комментарии должны рендериться быстрее и доставлять удовольствие всем, а не только обладателям топовых MacBook Pro c M1 Max.



Давайте посмотрим, как работали комментарии полгода назад, до того, как мы начали работу по оптимизации.
Читать дальше →
How to Increment and Decrement Number Using Vue 3 Composition Api

https://dev.to/larainfo/how-to-increment-and-decrement-number-using-vue-3-composition-api-48c7
In this tutorial we will create simple vuejs counter app using options api and composition api.
Quick Way to Start Project with Vite Vue 3 Headless UI Tailwind CSS



Simple Vue 3 Counter App using (Options Api) Example




Counter.vue


<template>
<div class="flex items-center justify-center gap-x-4">
<button
class="px-4 py-2 text-white bg-blue-600 focus:outline-none"
@click="increment">
Increment
</button>
{{ number }}
<button
class="px-4 py-2 text-white bg-red-600 focus:outline-none"
@click="decrement">
Decrement
</button>
</div>
</template>
<script>
export default {
data() {
return {
number: 0,
};
},
methods: {
increment() {
this.number++;
},
decrement() {
this.number--;
},
},
};
</script>






Vue 3 Counter App using (Composition Api) Example




Counter.vue


<template>
<div class="flex items-center justify-center gap-x-4">
<button
class="px-4 py-2 text-white bg-blue-600 focus:outline-none"
@click="increment">
Increment
</button>
{{ number }}
<button
class="px-4 py-2 text-white bg-red-600 focus:outline-none"
@click="decrement">
Decrement
</button>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const number = ref(0);
function increment() {
number.value++;
}
function decrement() {
number.value--;
}
return { number, increment, decrement };
},
};
</script>
Intro To Using Pinia For State Management In VueJS

https://dev.to/aaronksaunders/intro-to-using-pinia-for-state-management-in-vuejs-1n39
Intro To Using Pinia For State Management In VueJS
Pinia - The Vue Store that you will enjoy using... Intuitive, type safe, and flexible Store for Vue
I guess this is the new goto for state management in Vue3 and what is really awesome is that it works great with vue-devtools
This is a simple application that allows you to add students to and array that is managed in the global store and then perform the traditional CRUD actions against the store.
We show how to subscribe to changes in the store for updating the user interface
We discuss some of the benefits of this approach and its integration of typescript and how great it works with the vue-devtools.






Source Code






aaronksaunders
/
vite-pinia










Vue 3 + Typescript + Vite
This template should help get you started developing with Vue 3 and Typescript in Vite. The template uses Vue 3 <script setup> SFCs, check out the script setup docs to learn more.

Recommended IDE Setup


VSCode + Volar



Type Support For .vue Imports in TS
Since TypeScript cannot handle type information for .vue imports, they are shimmed to be a generic Vue component type by default. In most cases this is fine if you don't really care about component prop types outside of templates. However, if you wish to get actual prop types in .vue imports (for example to get props validation when using manual h(...) calls), you can enable Volar's .vue type support plugin by running Volar: Switch TS Plugin on/off from VSCode command palette.




View on GitHub
Pros and Cons of Vue.js Development Services

https://dev.to/steven_d_gital/pros-and-cons-of-vuejs-development-services-14hi
For IT organizations, it is crucial to use innovative technologies for their clients to drive revenue. Several times people are discussing the benefits of using the Vue.js programming language instead of any other and will get the conclusion that working with experienced Vue.js developer is always a better idea.
In the article, we will discuss Vue.js, the strengths and weaknesses of experts of Vue.js, and features and functions Vue.js offers for high-quality application development. Stay tuned!



What is Vue.js development?

Vue.js is developed by Evan You and It is a JavaScript-based framework first released in 2014. It is a framework to develop single-page applications. But within time, the range of Vue.js development expanded significantly.
Vue.js framework is very flexible. Vue.js can perform equally well in any kind of app development and web development.



Pros of Vue.js development

Vue.js framework offer infinite advantages compare to others. We will have a look at those advantages in this article.
Lightweight
Lightweight is one of the important pros of Vue.js that developer is looking for while developing. Vue.js is very convenient for developers to use for any kind of complex project.
Due to the lightweight of Vue.js, Installation and loading will be faster and it is good from the perspective of SEO and UX. Vue.js developers need to spend less time on optimization.
User-friendly
Many experts have to say that Vue does not need a steep learning curve, which is more easier and beneficial for fresher. With the not on the learning curve, Vue.js only needs the knowledge of HTML, JavaScript, and CSS. Vue.js offers the browser plugin under Chrome and Firefox, which make things easier for developers.
Reusable
Vue.js can be reusable for developers who have enough experience and tech-savvy. Vue.js helps programmers to write their own code so they can use it for various functions if needed.
Ease of use
One of the main reasons behind the success of Vue.js is it is easy to use with minimal effort. Vue.js has all the necessary codes in one file. With such easy use and flexibility, developers can develop any kind of structure for applications.
Integration
Vue.js uses syntax and virtual DOM like Angular in the same way. According to Evan You, Angular offers data-managed DOM and data binding, It is just amazing.
Vue.js developers don’t have to match with DOM on their own. This makes the Vue.js development easier.
Compatibility
To facilitate integration with existing applications, Vue.js used HTML to render objects. Vue.js is more flexible compared to other frameworks as it allows developers to write their own discretion with JSX, HTML, or JS. Based on the structure, Vue.js is similar to React and Angular. So you can easily switch from Angular or React to Vue.js.
Customization
Vue.js offer developers the easy access of all the features and functions. Each part of framework performs its function, So you can quickly adapt and implement the changes if needed.



Cons of Vue.js development

We all know that every framework has some cons, no framework could be perfect. And Same goes with Vue.js framework.

Lack of plugins;
Limitations in making use of the community;
Difficulties with mobile support;
Lack of scalability;
Difficulties with two-way binding;
Lack of highly experienced experts;
Excessive code flexibility.




Bottom line

If you have a wish to develop functional SPA or UI, pros of Vue.js always comes in first. Whether you want to develop the small project or large small, Vue.js will be always a perfect choice for development work.
If you want to inquire about Vue.js development services, Contact the best Vue.js development company and Hire Vue.js developer. Experience and talented Vue.js developers will help you to achieve your goals and profitable projects.
Looking at the new v-memo directive in Vue 3.2

https://dev.to/reegodev/looking-at-the-new-v-memo-directive-in-vue-32-5d6d
The release of Vue 3.2 introduced some new functionalities, mainly related to performance and optimisations. One of these features is a new directive called v-memo



What is v-memo?

v-memo, as the name suggests, is a new directive related to the memoization of parts of a template.

If you are not familiar with the term "memoization", wikipedia describes it as:

In computing, memoization or memoisation is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again

In Vue this description sounds really like what computed properties already do.

In fact v-memo can be seen as a computed property for parts of a template!



Using v-memo

v-memo accepts a single parameter, which should be an array of dependencies. The element that uses this directive and all its descendants will only be re-rendered when one of the dependencies change.

For example:



<div v-memo="[dep1, dep2]">
...
</div>


Note that if you don't provide dependencies , ie:v-memo="[]", you obtain the same functionality as v-once.



Examples

Since v-memo is mainly useful for performance reasons, one of the best scenarios where you'd want to use it is when rendering huge lists of items with v-for:



<div v-for="item in list" :key="item.id" v-memo="[item.id === selected]">
<p>ID: {{ item.id }} - selected: {{ item.id === selected }}</p>
</div>


In this example we are telling v-memo to only re-render an item if it has been selected or deselected, all other items will be skipped entirely.

We don't need to include item.id in the dependency array since the sub-template of every item is already keyed, so it generates a separate sub-tree.

Another thing to keep in mind is that v-memo is only useful in a v-for if you are using some kind of interpolation. If for example you are rendering a list of components like <MyComponent v-for="item in list" :key="item.id" v-memo />, you are not going to benefit from v-memo as the diffing is made inside each component.
I've prepared an example on StackBlitz that shows visually how v-memo helps with performance in lists: https://stackblitz.com/edit/vue-v-memo
TIL about specific Array combination types

https://dev.to/vanquard/til-about-specific-array-combination-types-28bo
Okay, so its not actually called "specific Array combination types", but that was the best description I had for it, before I looked it up.

Its actually called "Tuple Types" and the documentation can be found here: https://www.tutorialsteacher.com/typescript/typescript-tuple
I'll come back to why this blew my mind today, but first, lets scroll back a bit, to some of my first steps into JS/TS programming. I started my programming career in Java, and one of the things that annoyed the hell out of me, was the fact that I could only have 1 object returned from a function (This was before the Pair class was introduced).
But in JS we can easily just return an array with 2 values:



const someFunction = () => {
return ['Mathias', 28];
}


And combined with some destructuring on the recieving, it was all nice and easy:



const [myName, myAge] = someFunction();





Adding types

Until today I never had to add types onto a scenario like this, usually when I work with arrays, I either just do a basic string[], or when its required in complex object scenarios: Array<{name: string, age: number}>.

But with the tuples we can actually avoid naming them and just say the return type for our function is [string, number]:



const someFunction = (): [string, number] => {
return ['Mathias', 28];
}





Vue relation

I came across this when I working with Vue2 combined with TS, and was trying to create a v-for loop over a Map, but Vue2 did not support this, so I had to come up with a different approach that supported the same end goal.
So this is where the new tuples came in handy! Given an example with some data in a Map:



const map = new Map<string, object>();
map.set('key1', {data: 'lots of data'});
map.set('key2', {data: 'more data'});


I could then destructure it into an array like so:



const asArray = ...map.entries();
// Yielding:
[
['key1', {data: 'lots of data'}],
['key2', {data: 'more data'}],
]


And in order to Type this we now have:



const asArray: Array<[string, object]> = ...map.entries();


Thank you for reading this far, hope you gained something from this post.
NuxtJS v.2.15.8. How to hide private keys?

https://dev.to/vadiminsk/nuxtjs-v2158-how-to-hide-private-keys-3h62
Hello everyone! Currently I am working on PWA project. We build pwa with nuxt and drupal as backend. So I have a lot of secrets from backend and don`t know where store it.

Can you share your best practices?
Simple Black Friday

https://dev.to/core_ui/simple-black-friday-1eep
Not long ago, a guy, let’s name him “Kyle” asked us about CoreUI’s Tips for developers to create stunning web or app.
Answer was easy: “keep it simple” :)
“Everything should be made as simple as possible, but no simpler.”

Albert Einstein
You probably know Steve Krug’s “Don’t let me think” — it also a “bible” for CoreUI’s team. When you keep your design simple, then you’ll easily understand the principles of intuitive navigation and information design.

There’re too many overloaded products available on the market, that’s why we’ve always wanted to keep CoreUI as simple as it’s possible.

So we decided to master a CoreUI as one, comprehensive ecosystem or rather tool for the most significant UI needs.

When designing a stunning web or an app, it’s good to stick to valuable tools which will make your work easier. As an example, we can have “CoreUI’s Triada”:

Admin Templates
UI Components
Icons

They are all available for the most popular frameworks like Angular, Vue, Bootstrap and React. Such universal tools let the designer to be more flexible when working on different projects.
Keep it simple and responsive — the rest will follow.
PS Black Friday obliges… If you’re ready for -70% bounce here: Simple CoreUI Black Friday
A Vue wrapper for HubSpot Forms

https://vuejsexamples.com/a-vue-wrapper-for-hubspot-forms/
A Vue wrapper for HubSpot Forms
Webpack/Rollup/Vite plugin to add multiple root-node support to Vue 2 SFCs

https://vuejsexamples.com/webpack-rollup-vite-plugin-to-add-multiple-root-node-support-to-vue-2-sfcs/
Webpack/Rollup/Vite plugin to add multiple root-node support to Vue 2 SFCs
Petite-vue: 6kb subset of Vue optimized for progressive enhancement

https://vuejsexamples.com/petite-vue-6kb-subset-of-vue-optimized-for-progressive-enhancement/
Petite-vue: 6kb subset of Vue optimized for progressive enhancement