Научете Vue.js в този безплатен курс! ? ✨

Нека направим нещо Vueseful

Преди да стигна до статията, просто искам да споделя, че изграждам продукт и бих искал да събера някои данни за това как да обслужваме по-добре уеб разработчиците. Създадох кратък въпросник, който да проверя преди или след четенето на тази статия. Моля, проверете - благодаря! И сега, обратно към нашето редовно планирано програмиране.

Здравей Интернет!

Може да не знаете какво е Vue - и това е добре - и по дяволите, може би не, определено не, да знаете кой съм! Аз съм Зайдек и съм опитен графичен дизайнер и програмист. Току-що пуснах безплатен курс, за да помогна на разработчиците да научат някои Vue! Тук съм, за да ви осветя за всички възможности, които предлага обучението и използването на тази невероятна рамка с отворен код.

В тази статия описвам подробно как да мисля за Vue. Също така повтарям градивните елементи, необходими за започване на програмирането на статични и динамични уебсайтове с порядък по-лесно, отколкото с ванилов JavaScript. ? Vue е едновременно парадигма за писане на уеб приложения и идиоматично ръководство за обучение и програмиране на JavaScript.

Аз също преподавам JavaScript? ✨, необходим за започване на току-що пуснатия курс на Vue. Научете Vue от основите и как също да изградите няколко неща. Кликнете тук, за да се регистрирате безплатно!

Курсът се преподава на Scrimba.com, който е нов и интерактивен уебсайт за обучение и споделяне на кодиране . Екранните предавания могат да бъдат прекъсвани и редактирани, което прави ученето активно и забавно за експериментиране.

Vue не е едно нещо

Структурата може да се разглежда като набор от инструменти за общо ползване, оборудван с инструменти, които решават различни проблеми, но всички заедно помагат за някаква задача. Тази задача, що се отнася до Vue, създава лесно поддържаеми и идиоматични уеб приложения - наистина - и се забавлява, докато сме в това!

Нека да поставим нещата в перспектива. Vue може да бъде толкова просто, колкото таг на скрипт, който можем да включим в нашите уебсайтове, за да ги превърнем в уеб приложения. Но това може да бъде и цяла екосистема, която разчита на изграждащ процес, за да улесни инженерните сложни и мощни уеб приложения.

В тази статия и в курса се фокусирам върху изучаването на основните концепции, които Vue представя, и предполагам, че няма познания за командния ред или какво е процес на изграждане.

Какво обхваща курсът

Курсът е от три части:

  1. изучаване на минималния JavaScript, необходим за започване на работа с Vue
  2. изучаване на основните концепции на Vue и
  3. преглед на още два разширени примера (две сладки и забавни уеб приложения, които направих: Div на Schrödinger? и? Color Picker).

Това, което харесвам в Vue е, че той предлага някои интересни идеи за това как да мислим и как да изграждаме уеб приложения. Има няколко идеи, които според мен са най-интересни - въпреки че това не предполага всичко, което Vue може да направи:

  • разделяне на данните от DOM
  • идиоматичен JavaScript
  • шаблониране и базиран на компоненти HTML
  • управление на обработка на събития

Но преди да можем да влезем в това, нека първо разгледаме как да свържем Vue чрез прост скриптов маркер към уебсайт:

Можете да мислите за уеб приложението като за вътре или върху уебсайт. Така че уеб приложението започва живота си в

p">, where from inside the script tag it is plugged in via new Vue({ el: "#app" }). That is how we create a relationship from the JavaScript to the HTML (where el is short for element).

This is the first of what are known as options, and Vue supports a lot of options, such as data and methods. These are analogous to variables and functions for our web app.

Note: Vue comes in two flavors: ? there’s both the development and production version. The development version emits detailed error messages and warnings to support developers while working in Vue. The production version is optimized for speed and size.

In addition to all of this, there’s an official Chrome extension that makes managing the app’s state and debugging painless.

Separating the data from the DOM

Original text


As mentioned earlier, one great suggestion Vue proposes is separating the data from the DOM. DOM stands for document-object-model, which can be thought of as the tree of elements that compose our website. The text in between the opening and closing elements is what I’m referring to as the data. In Vue we don’t hardcode it — we separate it and put in the aforementioned data object from inside of our Vue instance.

This idea is also referred to as the Virtual DOM. This might seem insignificant, but the truth is that having the data in one place means that we know how and where to update it. And because Vue is reactive, whenever we update said data, that change gets propagated throughout our web app. Because of this relationship, data can be thought of as much more alive in Vue than in vanilla HTML.

These ideas are explored in the third screencast.

Idiomatic JavaScript

For me, Vue makes JavaScript a language worth learning, because it makes sense of JavaScript. What I mean is that from inside of a new Vue({ ... }) is how and where we learn to wrangle JavaScript. Variables are key-value pairs attached to the data object as shown above, and functions are attached as key-value pairs attached to a second object: methods. And both objects data and methods are optional — remember, these are our web app’s options.

But Vue goes a lot further: Vue features a lot of options that come in the form of objects we hook into in our Vue instance. Altogether, this resembles an idiomatic guide and approach to programming in JavaScript. Therefore, few architectural decisions are left for the programmer. This means that writing and reading Vue has a sort of coherence and elegance that makes it easier to pick up than deconstructing how a vanilla JavaScript app works.

These ideas are explored in the fourth screencast.

Templating HTML

Most people wouldn’t consider HTML a programming language. But I think a reasonable definition of the purpose of a programming language is this: to interpret and transform data, such as reading and compiling source code.

Given Vue’s attributes, such as v-for, v-if, and so on, for me HTML begins to resemble a programming language with control-flow. This means that we can better control the flow of our program’s data (for example, our website’s content or what I keep calling the data).

For what it’s worth, templating frameworks, like Jekyll and Hugo, were created to aid developers with authoring static-based websites using a kind of control-flow. As nice as this is, it’s limited to static websites, because these frameworks compile to HTML rather than interpret HTML.

Having access to realtime control-flow, like for-loops and if-statements, means that Vue can do a lot more and do it in realtime. This is one of the big differences between websites and web apps (static versus dynamic content).

These ideas are explored in the fifth screencast.

Components and props

Something that took me far too long to appreciate is the difference between variables and properties. Variables store data, whereas properties are variables attached to an object in JavaScript. So components can be thought of as HTML mixins. A what? A mixin is like a function, but instead of returning data, it mixes-in data into the document. For example, it writes HTML for us so we don’t have to repeat ourselves!

And this isn’t a small thing. The benefit of components and props in Vue means we can refactor entire HTML code blocks into one-liners that can be customized via props. This means we can now author custom elements that expose access to their internals without overcomplicating the public HTML. This is a big win for both maintainable and readable code.

These ideas are explored in the sixth screencast.

Managing event-handling

While everything we’ve talked about so far is fascinating, it doesn’t speak to user-interaction, which is one of the key differences between a website versus a web app. A website conventionally means something that is more-or-less static and isn’t designed or intended to interact with the user much, outside of perhaps collecting data. In an actual web app, something reminiscent of a native app, interaction is paramount. ? This idea is also referred to as a dynamic website or web app.

Since Vue is both a framework and an ecosystem, it has idiomatic solutions for this, too. The simplest one that I teach in the course is the @click="function()" handler which we plug into an element as an HTML attribute. This simple snippet gives us a means to interact with our data, as simple as an attribute that we plug into an element. This means that we can defer to JavaScript and not HTML or CSS for rich user-interaction.

These ideas are explored in the seventh screencast.

There’s a lot more to learning Vue, so I wrote two more articles on the subject matter. Please, after this article, have a look!

Vue makes the web make sense

Before Vue, I was acquainted with HTML and CSS. I was comfortable enough to make some alluring websites, but nothing more. I explored some frameworks (like those I discussed in this article concerning static compilation), and peered into Angular and React, but I didn’t get the right feeling when exploring those. What I wanted was something lightweight and intuitive, and I believe I’ve found that with Vue.

In the end, it doesn’t matter which tools we use if we can create what we set out to build. But the thing is, it’s hard to separate the tools from the thinking used to build a product or service. This is both a good and bad thing. On the one hand, it can make us narrow-minded. But on the other end of the spectrum, the tools we use can also serve as a teaching instrument for learning new and interesting ideas. I love tools that can’t help but teach me at the same time, and I couldn’t recommend Vue more for this reason!

So please, go out into the beautiful world and learn you some Vue! You can(!) make amazing things and even change people’s lives, even your own. And if it helps, try the free course!