create account

Universal Vue.js application with Nuxt.js part#10 Access the state with mapState and $store, Create search sytem by duski.harahap

View this thread on: hive.blogpeakd.comecency.com
· @duski.harahap · (edited)
$44.00
Universal Vue.js application with Nuxt.js part#10 Access the state with mapState and $store, Create search sytem
![ezgif.com-video-to-gif.gif](https://ipfs.busy.org/ipfs/QmYWB6hLTJiivAaoVxPxXLuVrogs9krdeq9bS6qLaMkfSu)



#### Repository
https://github.com/nuxt/nuxt.js

#### What Will I Learn?
- Access the state with ```mapState()``` in Vuex
- Access the state with ```$store``` in Vuex
- Create a search system
- Computed property

#### Resources
- Nuxt.js Website - https://nuxtjs.org/
- Nuxt.js Github. - https://github.com/nuxt/nuxt.js
- Axios- https://github.com/axios/axios
- JSON Placeholder- https://jsonplaceholder.typicode.com/
- Vuex - https://github.com/vuejs/vuex


#### Difficulty
Intermediated

### Tutorial Contents

This is the last series of CRUD Nuxt.js, Wwe have learned a lot about Nuxt.js in the previous tutorial we have learned the method of edit and update, in this tutorial I will add system search on ***Crud Nuxt*** application that we have created. We will use ```computed: {}``` property. for those of you who are familiar with Vue.js surely you also know ```computed: {}``` property. there will be changes we will make to adjust to our current code structure. for that we just start from to tidy up our code structure.


### Access the state through ```$store```

In the previous tutorial, we use ```mapState()``` to access the state on **Vuex**. but now we will learn how to access State by using ```$store```, we will change our code like the example below:

- **With ```mapState()```:**

``` javascript
 computed: mapState([
      'countries'
    ]),
```
If we want to access the **state in Vuex** by using **mapState**, We can directly put it on the ```computed:{}``` property and we can enter the state name we want to access, as a parameter of ```mapState()```. If the state we want to access more than one, we can pass it as an array ```mapState(['state1', 'state2','state3'])```.
<br>
- **With ```$store```**

There is another way if we want to access the state other than using ```mapState()```, we can access **the state** via ```$store.state```, to access the state using ```$store``` we must create a local variable in the ```data(){ }``` to store data from the state, here is an example:


``` javascript
data(){
      return{
        .....,
        .....,
        itemCountries : this.$store.state.countries
    },
 computed:{
      searchCountries(){
        return this.countries
      }
 }
```
- We create a local variable ```itemCountries``` to store the value of ```this.$store.state.countries```, ```countries``` is the name of the state name in **Vuex**.

- Then in the ```computed: {}``` property, we will create a function ```searchCountries()``` that returns ```return this.countries```, the value of the local variable in the ```data () {}```. 

- After we set state, we will do the data looping in **v-for** in the component. We'll see the difference using **mapState** and **$store**.

**With mapState:**
``` html
<div class="col-sm-6">
 <h3>List Of Countries</h3>
 <div class="alert alert-primary" role="alert" v-for="item in countries" :key="item.id">
    <p>Country : {{item.name}}</p> 
    <p>Capital City: {{item.city}}</p>
    <button class="btn btn-warning" style="margin-right: 10px;" @click="editData(item)">Edit</button>
     <button class="btn btn-danger" @click="doDelete(item.id)" >Delete</button>
 </div>  
</div>
```
```countries``` is the name of the state we access through ```mapState()```.

**With $store:**

``` html
<div class="col-sm-6">
 <h3>List Of Countries</h3>
 <div class="alert alert-primary" role="alert" v-for="item in searchCountries" :key="item.id">
    <p>Country : {{item.name}}</p> 
    <p>Capital City: {{item.city}}</p>
    <button class="btn btn-warning" style="margin-right: 10px;" @click="editData(item)">Edit</button>
     <button class="btn btn-danger" @click="doDelete(item.id)" >Delete</button>
 </div>  
</div>
```
```searchCountries``` is a function name in the computed property that serves to return the value of the local variable in the ```data() {}```.

**searchCountries()**
``` javascript
 computed:{
      searchCountries(){
        return this.itemCountries
      }
}
```
If we run our application we should not get different results. We can see the results as shown below.

![ezgif.com-video-to-gif (3).gif](https://ipfs.busy.org/ipfs/QmcupA1rU8QtrN52togZAVZik4wcFkzNmqrdt1rv7u7uk1)
<br>
### Create a search system
After we see the difference of **mapState** and **$store**, we will make the system search by using the function ```searchCountries()``` we have created earlier in ```computed: {}```.
<br>
- **Create input search**

We will start by making the input search on the component that will be used by the user, in the input text, we will put ```v-model = "searchKey"``` to bind it with the local variable we will create in the ```data() {}```.

**Example:**
``` html
 <div class="col-sm-6">
    <h3>List Of Countries</h3>
    <div class="form-group">
       <input type="text" class="form-control" id="search" placeholder="Search Country" v-model="searchKey">
     </div>
     <div class="alert alert-primary" role="alert" v-for="item in searchCountries" :key="item.id">
     <p>Country : {{item.name}}</p> 
     <p>Capital City: {{item.city}}</p>
     <button class="btn btn-warning" style="margin-right: 10px;" @click="editData(item)" >Edit</button>
     <button class="btn btn-danger" @click="doDelete(item.id)" >Delete</button>
    </div>  
</div>
```
<br>
**Result:**
![Screenshot_10.png](https://ipfs.busy.org/ipfs/QmZBRvPRm5QhKWmMdLCsASM1XY9qbBDWsnXsUh6JuiCFTg)
<br>
- **Create local variable in ```data()```**

After we create the input text in the component and add the **v-model** we will create a variable that will store the input data. We will store the data in ```searchKey:''``` according to the variable name in ```v-model = "searchKey"```.

**Example:**

``` javascript
data(){
      return{
        ......,
        ......,
        searchKey:''
    },
```
<br>
- **Create search function in ```computed:{}```**

Then we will create a search system for the function we have created earlier that is ```searchCountries()```.

**Example:**

``` javascript
computed:{
 searchCountries(){
   return this.itemCountries.filter(country => 
     country.name.toLowerCase().indexOf(this.searchKey.toLowerCase()) !== -1 || country.city.toLowerCase().indexOf(this.searchKey.toLowerCase()) !== -1
     )
   }
}
```
- We will create the ```filter()``` to filter the values ​​in the ```country.name``` object, then match the ```indexOf(this.searchKey)```.
- We can make a callback function with object ```country```, then we do the ```toLowerCase()``` function on the ***country object*** and ***this.searchKey*** to make the character to ***lower case***.
- We can make logic operator ```||``` **(or)** to search for objects from ***country.name*** and ***country.city***, so later we can do a search based on the name of **the country** and **the name of  state capital**.
- and do not forget to return the value with ```return```. but before that we will check first whether the search has a result or not by the way ```!== -1```.


to see the results of the learning we have done, we can run our Nuxt.js application to see the results as shown below.

**The Result**
![ezgif.com-video-to-gif.gif](https://ipfs.busy.org/ipfs/QmYWB6hLTJiivAaoVxPxXLuVrogs9krdeq9bS6qLaMkfSu)

We can see in the picture, we have created a search system in the Nuxt.js application that we created. I hope you can develop it better. thank you for following my tutorial so far. hopefully this tutorial can help you.

#### Curriculum
[Learn Nuxt#1 Nuxt structure, Global CSS, Request API](https://steemit.com/utopian-io/@duski.harahap/universal-vue-js-application-with-nuxt-js-part-1-nuxt-structure-installation-and-configuration-global-css-and-css-frameworks)
[Learn Nuxt#2 Vuex in Nuxt.js, Classic Mode and Modules Mode](https://steemit.com/utopian-io/@duski.harahap/universal-vue-js-application-with-nuxt-js-part-1-vuex-in-nuxt-js-classic-mode-and-modules-mode)
[Learn Nuxt#3 Create components, Reusable components and Nuxt-link](https://steemit.com/utopian-io/@duski.harahap/universal-vue-js-application-with-nuxt-js-part-3-create-components-in-nuxt-js-reusable-components-nuxt-link)
[Learn Nuxt#4 Dynamic components, Props, Transition page, Dynamic pages](https://steemit.com/utopian-io/@duski.harahap/universal-vue-js-application-with-nuxt-js-part-4-dynamic-components-props-transition-page-dynamic-pages)
[Learn Nuxt#5 Create Database API, Request data, Setup Port](https://steemit.com/utopian-io/@duski.harahap/universal-vue-js-application-with-nuxt-js-part-5-create-database-api-request-data-setup-port-database-and-nuxt-js-application)
[Learn Nuxt#6 Create Store in Vuex, Request data in Vuex, Data centralized](https://steemit.com/utopian-io/@duski.harahap/universal-vue-js-application-with-nuxt-js-part-6-create-store-in-vuex-request-data-in-vuex-data-centralized)
[Learn Nuxt#7 mapActions, Submit data, Process data with Vuex](https://steemit.com/utopian-io/@duski.harahap/universal-vue-js-application-with-nuxt-js-part-7-mapactions-submit-data-process-data-with-vuex)
[Learn Nuxt#8 Learn how to write mapActions, Delete data from API, Delete data with Vuex](https://steemit.com/utopian-io/@duski.harahap/universal-vue-js-application-with-nuxt-js-part-8-learn-how-to-write-mapactions-delete-data-from-api-delete-data-with-vuex)
[Learn Nuxt#9 Put method,Edit data and Delete data from API](https://steemit.com/utopian-io/@duski.harahap/universal-vue-js-application-with-nuxt-js-part-9-put-method-edit-data-and-delete-data-from-api)


#### Proof of Work Done
https://github.com/milleaduski/learnNuxtjs
πŸ‘  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 45 others
properties (23)
authorduski.harahap
permlinkuniversal-vue-js-application-with-nuxt-js-part-10-access-the-state-with-mapstate-and-usdstore-create-search-sytem
categoryutopian-io
json_metadata{"community":"busy","app":"busy/2.5.3","format":"markdown","tags":["utopian-io","tutorials","nuxtjs","vuejs","javascript"],"users":["click","duski.harahap"],"links":["https://github.com/nuxt/nuxt.js","https://nuxtjs.org/","https://github.com/nuxt/nuxt.js","https://github.com/axios/axios","https://jsonplaceholder.typicode.com/","https://github.com/vuejs/vuex","https://steemit.com/utopian-io/@duski.harahap/universal-vue-js-application-with-nuxt-js-part-1-nuxt-structure-installation-and-configuration-global-css-and-css-frameworks","https://steemit.com/utopian-io/@duski.harahap/universal-vue-js-application-with-nuxt-js-part-1-vuex-in-nuxt-js-classic-mode-and-modules-mode","https://steemit.com/utopian-io/@duski.harahap/universal-vue-js-application-with-nuxt-js-part-3-create-components-in-nuxt-js-reusable-components-nuxt-link","https://steemit.com/utopian-io/@duski.harahap/universal-vue-js-application-with-nuxt-js-part-4-dynamic-components-props-transition-page-dynamic-pages"],"image":["https://ipfs.busy.org/ipfs/QmYWB6hLTJiivAaoVxPxXLuVrogs9krdeq9bS6qLaMkfSu","https://ipfs.busy.org/ipfs/QmcupA1rU8QtrN52togZAVZik4wcFkzNmqrdt1rv7u7uk1","https://ipfs.busy.org/ipfs/QmZBRvPRm5QhKWmMdLCsASM1XY9qbBDWsnXsUh6JuiCFTg","https://ipfs.busy.org/ipfs/QmYWB6hLTJiivAaoVxPxXLuVrogs9krdeq9bS6qLaMkfSu"]}
created2018-07-30 06:47:12
last_update2018-07-30 06:51:27
depth0
children2
last_payout2018-08-06 06:47:12
cashout_time1969-12-31 23:59:59
total_payout_value33.407 HBD
curator_payout_value10.590 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length9,605
author_reputation60,094,717,098,672
root_title"Universal Vue.js application with Nuxt.js part#10 Access the state with mapState and $store, Create search sytem"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id66,477,205
net_rshares25,652,662,515,802
author_curate_reward""
vote details (109)
@portugalcoin ·
$0.02
Thank you for your contribution.

- The difficulty level of this tutorial is basic.

Good job!!!

Your contribution has been evaluated according to [Utopian policies and guidelines](https://join.utopian.io/guidelines), as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, [click here](https://review.utopian.io/result/8/31111314).

---- 
Need help? Write a ticket on https://support.utopian.io/. 
Chat with us on [Discord](https://discord.gg/uTyJkNm). 
[[utopian-moderator]](https://join.utopian.io/)
πŸ‘  ,
properties (23)
authorportugalcoin
permlinkre-duskiharahap-universal-vue-js-application-with-nuxt-js-part-10-access-the-state-with-mapstate-and-usdstore-create-search-sytem-20180730t210752704z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"links":["https://join.utopian.io/guidelines","https://review.utopian.io/result/8/31111314","https://support.utopian.io/","https://discord.gg/uTyJkNm","https://join.utopian.io/"],"app":"steemit/0.1"}
created2018-07-30 21:07:51
last_update2018-07-30 21:07:51
depth1
children0
last_payout2018-08-06 21:07:51
cashout_time1969-12-31 23:59:59
total_payout_value0.020 HBD
curator_payout_value0.004 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length588
author_reputation598,828,312,571,988
root_title"Universal Vue.js application with Nuxt.js part#10 Access the state with mapState and $store, Create search sytem"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id66,560,727
net_rshares15,517,418,839
author_curate_reward""
vote details (2)
@utopian-io ·
Hey @duski.harahap
**Thanks for contributing on Utopian**.
We’re already looking forward to your next contribution!

**Want to chat? Join us on Discord https://discord.gg/h52nFrV.**

<a href='https://v2.steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1'>Vote for Utopian Witness!</a>
properties (22)
authorutopian-io
permlinkre-universal-vue-js-application-with-nuxt-js-part-10-access-the-state-with-mapstate-and-usdstore-create-search-sytem-20180802t071009z
categoryutopian-io
json_metadata"{"app": "beem/0.19.42"}"
created2018-08-02 07:10:09
last_update2018-08-02 07:10:09
depth1
children0
last_payout2018-08-09 07:10:09
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length305
author_reputation152,955,367,999,756
root_title"Universal Vue.js application with Nuxt.js part#10 Access the state with mapState and $store, Create search sytem"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id66,847,325
net_rshares0