📜 ⬆️ ⬇️

4 tips on working with Vue.js

Here are some tips for working with Vue.js that I have developed over the last year.


Use arrow functions in components.


ES6 gave us a new way to declare functions with convenient binding of the current scope. When using the old method, this may not refer to what you expect.


For example:


function Person () { this.age = 0; setInterval(function growUp () { // `this.age`   undefined //       //      Person console.log(this.age); }, 1000) } const Developer = new Person(); 

The growUp function has defined its scope and this inside does not refer to the Person object. To achieve the desired behavior, you can save the scope in a variable, or using the function .bind (context)


 //     that function Person () { var that = this; that.age = 0; setInterval(function growUp () { console.log(that.age); }, 1000) } //    bind function Person () { this.age = 0; setInterval(function growUp () { console.log(this.age); }.bind(this), 1000) } 

But the most convenient option would be to simply use the arrow function. It automatically binds the scope of the function to the parent scope.


 function Person () { this.age = 0; setInterval(() => { console.log(this.age); }, 1000) } 

That's better, isn't it?


Use single-file components


Single-file components (.vue) - one of my favorite features in Vue.js
They allow us to define reusable templates and parts of our application and reuse them. But to use them, you need the appropriate assembly tools.


(approx. Trans. All this is already configured and ready to work in the console utility Vue-cli ).


There are two ways to create Vue components.
For example:


 Vue.component('my-counter', { data () { return { count: 0 } }, methods: { add () { this.count += 1; } }, template: `<div> <div>{{ count }}</div> <button @click="add()">Increment</button> </div>` } }); 

Now the same, but using the .vue file


 <template lang="html"> <div> <div>{{ count }}</div> <button @click="add()">Increment</button> </div> </template> <script> export default { data () { return { count: 0 } }, methods: { add () { this.count += 1; } } } </script> 

On a small component, the advantages are not so obvious, but if you install the appropriate extensions in your editor, you will get excellent syntax highlighting, and it will also be easier for you to find the necessary component slice (from top to bottom go template, js, styles).


Global plugins


When developing large applications, you will everywhere use the functionality of some components inside others, so that each time you don’t import a .vue component into everyone who needs its functionality, it’s better to write it once and use it as a global plug-in.


We can make one component with all the functionality we need:


 <template lang="html"> <div> <user-container v-for="u in users"> <p>{{ sayHello(u.name) }}</p> </user-container> </div> </template> <script> import UserContainer from './UserContainer' //         export default { components: { UserContainer, }, methods: { sayHello (name) { return `Hello ${name}!` } }, computed: { users () { return this.$store.getters['users']() } } } </script> 

Or we can create a plugin and use it:


 import UserContainer from './UserContainer' const Plugin = { install (Vue, options) { // <g-user-container>       Vue.component('GUserContainer', UserContainer) Vue.mixin({ computed: { // `users`      users () { return this.$store.getters.users }, } }) // $sayHello is available within components Vue.prototype.$sayHello = function (name) { return `Hello ${name}!` } } } //     import Vue from 'vue' Vue.use(Plugin) new Vue({ //... }) 

Use this approach when you see that you are repeating the same functionality inside your components. Don't repeat yourself


Use Vuex to store state


Modern web applications use large amounts of data on the client and manage them. I have seen people just store all the data inside the components. This is a normal approach when you do not need access to the data of one component from another.


It is very tempting to use props to transfer data to components, or to use libraries to subscribe to events (Pub — Sub) to manage data in the application, but over time this leads to bloat of the code, and it becomes difficult to maintain your application.


Vuex comes in handy when your components need access to the same state. Instead of turning your code into hell, casting all the data through props, Vuex will allow you to store all the state of the application in yourself and give it access to the necessary components.


With Vuex, we can define state (data), getters, actions, and mutations that allow us to manipulate the data as we need it.


 import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ state: { movies: [], actors: [] }, getters: { movies: state => { return state.movies }, actors: state => { return state.actors } }, actions: { getMovies (context) { axios.get('/api/movies') .then((movies) => { context.commit('setMovies', movies) }) }, getActors (context) { axios.get('/api/actors') .then((actors) => { context.commit('setActors', actors) }) } }, mutations: { setMovies (state, movies) { state.movies = movies }, setActors (state, actors) { state.actors = actors } } }) new Vue({ el: '#app', store, render: h => h(App) }) 

Use Vuex inside the component:


 <template lang="html"> <div> <div v-for="m in movies"> <p>{{ m.name }}</p> <p>{{ m.description }}</p> </div> <div v-for="a in actors"> <p>{{ a.firstName }} {{ a.lastName }}</p> </div> </div> </template> <script> export default { mounted () { this.$store.dispatch('getMovies') this.$store.dispatch('getActors') }, computed: { movies () { this.$store.getters.movies }, actors () { this.$store.getters.actors } } } </script> 

Conclusion


Vue.js makes our work much easier, and makes the process of writing new features more enjoyable, but we need to spend some time studying the stack of related technologies and tools.


I hope you try Vue.js in your new project


')

Source: https://habr.com/ru/post/352540/


All Articles