Xem mẫu

6

Plugins – Building Your House
with Your Own Bricks
In the previous chapter, you learned how to manage the global application store using the
Vuex architecture. You learned a lot of new concepts and applied them. You also learned
how to create a store, how to define its state and mutations, and how to use actions and
getters. We brought our shopping list and Pomodoro applications to life using the
knowledge acquired during the chapter.
In this chapter, we will revisit Vue plugins, see how they work, and how they must be
created. We will use some existing plugins and create our own.
Summing it up, in this chapter, we are going to do the following:
Understand the nature of Vue plugins
Use the resource plugin in the shopping lists application
Create a plugin that produces white, pink, and brown noises and apply it to our
Pomodoro application

The nature of Vue plugins
Plugins in Vue.js are used for exactly the same purpose as they are used in any other scope:
to add some nice functionality that, due to its nature, cannot be achieved with the core
functionality of the system. Plugins written for Vue can provide various functionalities,
starting from the definition of some global Vue methods or even the instance methods and
moving toward providing some new directives, filters, or transitions.

Plugins – Building Your House with Your Own Bricks

In order to be able to use an existing plugin, you must first install it:
npm install some-plugin --save-dev

And then, tell Vue to use it in your application:
var Vue = require('vue')
var SomePlugin = require('some-plugin')
Vue.use(SomePlugin)

We can also create our own plugins. This is also easy. Your plugin must provide an
install method where you define any global or instance methods, or custom directives:
MyPlugin.install = function (Vue, options) {
// 1. add global method or property
Vue.myGlobalMethod = ...
// 2. add a global asset
Vue.directive('my-directive', {})
// 3. add an instance method
Vue.prototype.$myMethod = ...
}

Then it can be used just like any other existing plugin. In this chapter, we will use the
existing resource plugin for Vue (https://github.com/vuejs/vue-resource) and create
our own plugin that generates white, pink, and brown noises.

Using the vue-resource plugin in the
shopping list application
Open the shopping list application (the chapter6/shopping-list folder) and run npm
install and npm run dev. It's nice and clean, but it still uses the hardcoded list of the
shopping lists. It would be really nice if we were able to add new shopping lists, delete
them, and store the information on updated shopping lists so that when we restart the
application, the displayed information corresponds to the last we saw before restarting. In
order to be able to do that, we will use the resource plugin, which allows us to easily
create REST resources and call REST methods on them. Before starting, let's summarize
everything that we need to do in order to achieve this:
First of all, we need to have a simple server that contains some storage from
where we can retrieve and where we can store our shopping lists. This server
must provide the needed endpoints for all this functionality.
[ 200 ]

Plugins – Building Your House with Your Own Bricks

After creating our server and all needed endpoints, we should install and use the
vue-resource plugin to create a resource and actions that will call the methods
on the provided endpoints.
In order to guarantee the data integrity, we should call actions that update
server's state on each shopping lists update.
On the application start, we should fetch shopping lists from the server and
assign them to our store's state.
We should also provide a mechanism to create new shopping lists and delete the
existing ones.
Doesn't sound too difficult, right? Let's start then!

Creating a simple server
For the sake of simplicity, we will use a very basic and easy-to-use HTTP server that stores
data inside a regular JSON file. It is called json-server and it is hosted at https://github
.com/typicode/json-server. Install it in the shopping list application's directory:
cd shopping-list
npm install --save-dev json-server

Create a server folder with the db.json file inside it with the following content:
//shopping-list/server/db.json
{
"shoppinglists": [
]
}

This will be our database. Let's add the script entry to our package.json file so that we
can easily start our server:
"scripts": {
"dev": "node build/dev-server.js ",
"server": "node_modules/json-server/bin/index.js --watch
server/db.json",

},

Now, to start a server, just run the following:
cd shopping-list
npm run server

[ 201 ]

Plugins – Building Your House with Your Own Bricks

Open the browser page at http://localhost:3000/shoppinglists. You will see an
empty array as a result. This is because our database is still empty. Try to insert some data
using curl:
curl -H "Content-Type:application/json" -d '{"title":"new","items":[]}'
http://localhost:3000/shoppinglists

If you refresh the page now, you will see your new inserted value.
Now that we have our simple REST server up and running, let's use it in our shopping list
application with the help of the vue-resource plugin!

Installing vue-resource, creating resources, and
its methods
Before going deeper into the usage of the vue-resource plugin, check out its
documentation at https://github.com/vuejs/vue-resource/blob/master/docs/resour
ce.md. Basically, the documentation provides an easy way of creating resources based on
the given URL (in our case, it will be http://localhost:3000/shoppinglists). After
the resource is created, we can call get, delete, post, and update methods on it.
Install it in the project's folder:
cd shopping-list
npm install vue-resource --save-dev

Now let's create the entry point for our API. Inside an src folder of the shopping list
application, create a subfolder and call it api. Create an index.js file inside it. In this file,
we will import the vue-resource plugin and tell Vue to use it:
//api/index.js
import Vue from 'vue'
import VueResource from 'vue-resource'
Vue.use(VueResource)

Nice! Now we are ready to create ShoppingListsResource and attach some methods to
it. To create a resource using the vue-resource plugin, we just call a resource method on
Vue and pass the URL to it:
const ShoppingListsResource = Vue.resource('http://localhost:3000/' +
'shoppinglists{/id}')

[ 202 ]

Plugins – Building Your House with Your Own Bricks

The ShoppingListsResource constant now exposes all the methods needed for the
implementation of CRUD (Create, Read, Update, and Delete) operations. It is so easy to
use that we could basically export the resource itself. But let's export nice methods for each
of the CRUD operations:
export default {
fetchShoppingLists: () => {
return ShoppingListsResource.get()
},
addNewShoppingList: (data) => {
return ShoppingListsResource.save(data)
},
updateShoppingList: (data) => {
return ShoppingListsResource.update({ id: data.id }, data)
},
deleteShoppingList: (id) => {
return ShoppingListsResource.remove({ id: id })
}
}

The full code for the api/index.js file can be seen in this gist at https://gist.github.co
m/chudaol/d5176b88ba2c5799c0b7b0dd33ac0426.
That's it! Our API is ready to be used and to populate our reactive Vue data!

Fetching all the shopping lists the application
starts
Let's start by creating an action that will fetch and populate store's shoppinglists state.
After its creation, we can call it on the main App.vue ready state.
Define a constant in the mutation_types.js file as follows:
//mutation_types.js
export const POPULATE_SHOPPING_LISTS = 'POPULATE_SHOPPING_LISTS'

Now create a mutation. This mutation will just receive an array of shoppinglists and
assign it to the shoppinglists state:
//mutations.js
export default {
[types.CHANGE_TITLE] (state, data) {
findById(state, data.id).title = data.title
},

[ 203 ]

nguon tai.lieu . vn