Vue.js Series Tutorial 4:vuex

Source: Internet
Author: User

Original: Intro-to-vue-4-vuex

Translator: Nzbin

This is the fourth part of the JavaScript framework vue.js five tutorials. In this section, we will learn to use VUEX for state management. This series of tutorials is not a complete user manual, but rather a basic knowledge that gives you a quick overview of Vuejs and its uses.

Series Articles:
    1. rendering, directives, events
    2. Components, Props, Slots
    3. Vue-cli
    4. Vuex (Here you are!)
    5. Animations
Vuex

If you miss the part about components and VUE-CLI, you should read these sections before reading this article. Now that we've learned the basics about components, delivery states, and props, let's talk about Vuex, which is a good tool for state management.

Previously, we passed down the state from the top-level component, and there was no sharing of data between the sibling components. If they need to communicate with each other, we want to push the state in the application. This is possible! But once your program becomes complex, this approach is meaningless. If you have used Redux before, then all the concepts and implementations of VUEX are not unfamiliar to you. Vuex is the Redux in Vue. In fact, Redux can also be used with Vue, but it is more advantageous to use a tool specifically designed for Vue Vuex.

First, install Vuex:

npm install vuex

Or

yarn add vuex

I set this up: in the '/src ' directory, I created a directory called store (this is an option, you can also create a ' store.js ' file in the sibling directory), and then create a file named ' Store.js ' in it. The initial settings in ' Store.js ' are as follows (Vstore Sublime snippet):

Import vue from ' Vue ', import Vuex from ' Vuex '; Vue.use (VUEX); export Const STORE = new Vuex.store ({State  : {    key:value  }});

key: valueis a placeholder for the state data. In other cases, we have used the counter: 0 .

In the ' main.js ' file, we will perform the following update (bold to display the updated lines):

Import vue from ' Vue '; the import App from './app.vue ';  './store/store '; New Vue ({  el: ' #app ',  store:store,  Template: ' <App/> ', components  : {app}});

After the update, as in the previous component, we can put it data() as a state, and then we use or update the status in the following three ways:

    • Getters can display data statically in a template. In other words, getters can read the data, but it cannot change the state.
    • mutations allows the status to be updated, but is always synchronized. Mutations is the only way to change state data in the store.
    • Actions allow you to update the state asynchronously, but you need to use an already existing mutation. It can be useful if you need to perform different mutations in a specific order at the same time.

If you haven't been exposed before, it might be hard to understand why you're using asynchronous state changes, so let's look at what's going on in theory and then start the next part. If you run TUMBLR. If the page has a large number of long-running GIF pictures. You only want to load a portion of it each time, such as when the user scrolls the page to the bottom 200px, loading 20 images.

You need to use mutation to show the following 20. But there are not 20 behind, you don't know when to reach the bottom of the page. Therefore, in the program, create an event to listen for the scrolling position and then trigger the appropriate action.

The operation then retrieves the URL of the next 20 images from the database and adds the state of the 20 pictures to the mutation and then displays.

Essentially, Actions create a framework that requests data. They use consistent methods to apply the data in an asynchronous way.

The most basic example of abstraction

In the following example, the most basic implementation of each attribute is shown, so you can learn how to set it up and use it. A payload is an optional parameter that allows you to define the value of the component being updated. Don't worry, we'll show you a real-world case, and now it's important to understand the basic concepts.

' Store.js ':

Export Const STORE = new Vuex.store ({  state: {    counter:0  },  //show content, cannot change status  getters: {    Triplecounter:state = {      return state.counter * 3;    }  ,  //change state  //mutations is always synchronous  Mutations: {    //Displays the delivered payload payload, denoted by num    increment: (state, num) = {      State.counter + = num;    }  },   //Submit mutation, which is an asynchronous  actions: {    //shows the load payload passed, with Asynchnum (an object) representing    asyncdecrement: ( {commit}, Asyncnum) = {      SetTimeout () = {        //Asyncnum object can be a static value        commit (' decrement ', asyncnum.by) (}      , asyncnum.duration);}}  );

A good feature is that we can return the entire state object in mutations, but we don't have to do this, we only use what we need. Time Shuttle test (looking for errors in mutations) can still work.

In the component, we will use it for getters computed (which is important because value values have already been calculated) and methods used in dispatch to access mutations and actions:

' App.vue ':

Computed: {  value () {    return this. $store. Getters.value;  }},methods: {  increment () {    this.$ Store.dispatch (' increment ', 2)}  }

Alternatively, you can use the extension operator. I find it useful when you need a lot of mutations/actions:

Export Default {  //...  Methods: {    ... mapactions ([      ' increment ',///This.increment () is mapped to this. $store. Commit (' increment ')      ' Decrement ',      ' asyncincrement '    )  }}
A simple example

Let's take a look at the weather notification program, which has a small and simple state in its Vuex store. This is the warehouse for the sample code.

' Store.js ':

Import vue from ' Vue ', import Vuex from ' Vuex '; Vue.use (VUEX); export Const STORE = new Vuex.store ({State  : {    showweather:false,    template:0  },    mutations: {      toggle:state = State.showweather =!state.showweather,      updatetemplate: (state) = = {        state.showweather =!state.showweather;        State.template = (state.template + 1)% 4;}}  );

The state we set here showWeather , its initial value is false, because we do not want any animations to be executed immediately, only when the user taps the button. In mutations, we can toggle showWeather the state.

We also set the status template to 0. We will use this number in each weather component. So in mutations, we created a updateTemplate method named. It toggles showWeather the state at the same time and updates the value template after 1, but the value is 4 o'clock and then the click becomes 0.

App.vue:

 <template> <div id= "App" > ... <g id= "Phonebutton" @click = "updatetemplate" v-if= "!showweather" &G       T ... </g> <transition @leave = "Leavedroparea": css= "false" > <g v-if= "Showweather" &G        T <app-droparea v-if= "template = = = 1" ></app-droparea> <app-windarea v-else-if= "template = = 2" >< /app-windarea> <app-rainbowarea v-else-if= "template = = 3" ></app-rainbowarea> <app-tornado  Area v-else></app-tornadoarea> </g> </transition> </div></template> 
<script>  import Dialog from './components/dialog.vue ';  ...  Export Default {    computed: {      showweather () {        return this. $store. State.showweather;      },      template ( {        return this. $store. state.template;      }    ,    methods: {      updatetemplate () {        this.$ Store.commit (' updatetemplate ');      }    },    ...    Components: {      appdialog:dialog,      ...    }} </script>

' Dialog.vue ':

<script>export Default {  computed: {    template () {      return this. $store. state.template;    }  } ,  methods: {    Toggle () {This      . $store. Commit (' toggle ');    }  },  mounted () {      //enter Weather      Const TL = new Timelinemax ();    ...  }} </script>

In the code above, the APP component uses the showWeather show template in turn, and the Dialog component only switches the visibility of the component. In App.vue, we <template> show and hide different subcomponents based on the template values in the APP, using the conditional rendering we learned in the first chapter. In the App, we computed listen to changes in the state of the store by value, using the methods toggle() and updateTemplate() submitting the store's mutations.

This is a basic example, but you can learn how to handle complex programs with a large number of States, which facilitates managing all states in one place, rather than moving components up and down. Especially when communicating between sibling components.

If you want to learn more about Vuex, you can read this document. You can notice that we used the component in the last example, and there was a <transition> lot of animation. We'll start the discussion in the next section.

Vue.js Series Tutorial 4:vuex

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.