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

in utopian-io •  6 years ago  (edited)

ezgif.com-video-to-gif.gif

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

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():
 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']).

  • 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:

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:

<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:

<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()

 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

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: {}.

  • 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:

 <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>



Result:
Screenshot_10.png

  • 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:

data(){
      return{
        ......,
        ......,
        searchKey:''
    },


  • Create search function in computed:{}

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

Example:

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

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
Learn Nuxt#2 Vuex in Nuxt.js, Classic Mode and Modules Mode
Learn Nuxt#3 Create components, Reusable components and Nuxt-link
Learn Nuxt#4 Dynamic components, Props, Transition page, Dynamic pages
Learn Nuxt#5 Create Database API, Request data, Setup Port
Learn Nuxt#6 Create Store in Vuex, Request data in Vuex, Data centralized
Learn Nuxt#7 mapActions, Submit data, Process data with Vuex
Learn Nuxt#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

Proof of Work Done

https://github.com/milleaduski/learnNuxtjs

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

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, 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.


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

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.

Vote for Utopian Witness!