Home  >  Article  >  Web Front-end  >  Detailed explanation of plug-in status management implemented in vuejs

Detailed explanation of plug-in status management implemented in vuejs

韦小宝
韦小宝Original
2018-03-14 16:14:591814browse

This article talks about the implementation of plug-in state management in vuejs. If you don’t know about the implementation of plug-in state management in vuejs or are interested in the implementation of plug-in state management in vuejs, then let’s take a look at this article. Okay, enough nonsense. Let’s get to the point

#For novices, when they first came into contact with vuex, they only heard that it is very powerful, easy to use, and has various nb operations. Once you try to understand it When the time comes, it seems powerless. The same is true for me. When I first came into contact with it, I read documents and videos, but finally put it aside. When I came back to think about it after a while, I gained new knowledge and understanding.

First of all, if you want to truly master vuex, then you need to figure out these questions:

1.What is vuex?

2. Under what circumstances should vuex be used (that is, what kind of problems can vuex solve), and under what circumstances is it suitable to use vuex?

So let’s take a look at these two questions first:

What is vuex? The official website says: Vuex Is a state management pattern developed specifically for Vue.js applications. According to my popular understanding: vuex is used to manage some states between various components. It can be understood that these states are the public (shared) parts. At this time, any component can obtain status from it or trigger some behavioral events.

When is vuex used? The official website says: If you do not plan to develop a large single-page application, use Vuex can be cumbersome and redundant. It's true - if your app is simple enough, you're probably better off not using Vuex. A simple global event bus is enough for you. However, if you need to build a medium to large single page application, you will most likely consider how to better manage state outside the component, Vuex will become a natural choice.

Okay, now I will assume that you are developing a relatively large project, and vuex will be used in those places. Woolen cloth? As the complexity of the application increases, more and more data or component states will be transferred between components. For example: when component A enters component B (page A enters page B), it is often necessary to bring some If the parameters are passed, then you may choose to put them after the URL and pass them as parameters. If you don’t want to expose the parameters easily, you may save them in the session or local storage first, and then take them out when you enter the second page. . Yes, this is indeed a solution, and it is used a lot. But this is not a good method. At this time, you need vuex to help you. In addition, when you have a basic understanding of vuex, you will find that vuex management is based on modular thinking, which is very friendly to later management and maintenance of the project.

#so, now you have to have a deeper understanding of the core concepts of vuex. The following is a concept that I personally understand. First of all, it is recommended that you read the official document Vuex2.0 concept first.

Vuex The templated definition of Store in is as follows:

#1, state defines the data structure of the application, which is where the initialization data (state) is placed in vuex. It is equivalent to the data in the component used to store data.

 state:{
        todoLists:[],
    },

##2, getters is from the state Derive the state, such as getting the total number of todoLists in the state. In fact, it is equivalent to the computed property in vue, except that the getters are placed in vuex.

##

//Getters函数 接受 state 作为其第一个参数
  getters:{
      todoCount(state){
          return state.todoLists.length;
      }
  },

3, mutations is the only place where application status is allowed to be updated. Similar to the $on event in vue: each Each mutation has a string event type (type) and a callback function (handler). Note: mutations must be synchronous functions

//和Getters函数一样 接受 state 作为其第一个参数
  mutations:{
      //新増 TodoList item
      ONADDTODO(state,item){
          state.aTodos.push(item);
      },
      //删除 TodoList item
      ONDELTODO(state,index){
          state.aTodos.splice(index,1);
      },
      //设置 错误提示信息
      ONERROR(state,str){
          state.massage=str;
      }
  },
4,

actions Definition submission Description of trigger change information, Any asynchronous operation can be done in actions, a common example is to obtain data from the server, after the data acquisition is completed, store.commit() will be called (similar to $emit in vue) to invoke changes Status in the Store. You can use dispatch in components to issue Actions.

//Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,
    因此你可以调用 context.commit 提交一个 mutation,
    或者通过 context.state 和 context.getters 来获取 state 和 getters
  actions:{
      //提交 ONADDTODO
      onAddTodo(context,item){
          if(item.value!=""){
              context.commit("ONADDTODO",item);
              context.commit("ONERROR","");
          }else{
              context.commit("ONERROR","添加失败")
          }
      },
      //提交 ONDELTODO
      //可利用 ES2015 的 [参数解构] 来简化代码
      onDelTodo({commit},index){
          //commit=context.commit
          commit("ONDELTODO",index);
      }

  }
Vuex auxiliary function

1, Vuex.mapState(map : Array98c455a79ddfebb79781bff588e7b37e | Object): Object

Create a component's computed property to return the state in the Vuex store.
##2. Vuex.mapGetters(map: Array98c455a79ddfebb79781bff588e7b37e | Object): Object

Create the calculated property of the component and return the return value of the getter.
##3. Vuex.mapActions(map: Array98c455a79ddfebb79781bff588e7b37e | Object): Object

Create a component method to distribute action.

##4. Vuex.mapMutations(map: Array98c455a79ddfebb79781bff588e7b37e | Object): Object
Create component method to submit mutation.

For specific usage of Vuex auxiliary functions, please refer to: API documentation

TodoList example

After understanding the basic concepts of Vuex, we will create a todolist to familiarize ourselves with the entire usage process.

Use the vue-cli tool

Create the project directory and install vuex

vue init webpack-simple vue-vuex-todolist
npm install 
npm install vuex --save
npm run dev   //启动项目

Create a directory named store under the src directory to store state management related code. First create index.js

##

import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);

const store = new Vuex.Store({
    state:{
        massage:"",
        aTodos:[{value:"默认默认",id:0}],
    },
    getters:{
        nCounts(state){
            return state.aTodos.length;
        }
    },
    mutations:{
        //新増 TodoList item
        ONADDTODO(state,item){
            state.aTodos.push(item);
        },
        //删除 TodoList item
        ONDELTODO(state,index){
            state.aTodos.splice(index,1);
        },
        //设置 错误提示信息
        ONERROR(state,str){
            state.massage=str;
        }
    },
    actions:{
        //提交 ONADDTODO
        onAddTodo(context,item){
            if(item.value!=""){
                context.commit("ONADDTODO",item);
                context.commit("ONERROR","");
            }else{
                context.commit("ONERROR","添加失败")
            }
        },
        //提交 ONDELTODO
        onDelTodo({commit},index){
            commit("ONDELTODO",index);
        }

    },
    modules:{}
});

export default store;
## Add the Store instance to the constructed Vue instance in the #main.js file

##

import Vue from 'vue';
import App from './App.vue';
import store from './store';

new Vue({
  el: '#app',
  store,
  render: h => h(App)
})

Create a component named components in the src directory Directory to store vue components and create input.vue, list.vue files

input.vue

<template>
    <p class="form-group ">
      <input type="text" class="form-control"  placeholder="" v-model="value"  />
      <button type="buttom" class="btn btn-default" @click="addItem">Add Item</button>
    </p>
</template>
<script>
    export default{
        data(){
            return {
                value:"",
                id:0
            }
        },
        methods:{
            addItem(){
                let item={value:this.value,id:++this.id};
                this.value="";
                this.$store.dispatch("onAddTodo",item);
            }
        }

    }
</script>
<style lang="scss">
    %box{display:-webkit-box;-webkit-box-pack:center;-webkit-box-align:center;}
    .form-group{@extend %box;
        .form-control{-webkit-box-flex:1;}
    }
</style>

list.vue

<template>
    <p class="todolist">
      <ul class="list-group">
        <li class="list-group-item" v-for="(item,index) in aTodos" >
            <span>{{item.value}}</span>
            <button class="btn btn-default" @click="delItem(index)">删除</button>
        </li>
       </ul>
    </p>
</template>
<script>
    import {mapState} from "vuex";
    export default{
        data(){
            return {}
        },
        methods:{
            delItem(index){
                this.$store.dispatch(&#39;onDelTodo&#39;,index);
            }
        },
        computed:{
            ...mapState([
                &#39;aTodos&#39;
            ])
        }
    }
</script>
<style lang="scss">
    %box{display:-webkit-box;-webkit-box-pack:center;-webkit-box-align:center;}
    .list-group-item{display: -webkit-box;-webkit-box-align:center;
        span{
            display: block;
            -webkit-box-flex:1;
        }
    }
</style>

修改App.vue文件

<template>
  <p id="app">
    <h1>Vue.js Vue TodoList</h1>
    <hr>
    <todoInput />
    <todoList />
    <p>todoList 数量:{{todoCount}}</p>
    <pre class="brush:php;toolbar:false">{{$store.state}}

<script> import todoInput from &#39;./components/input.vue&#39;; import todoList from &#39;./components/list.vue&#39;; import {mapGetters} from "vuex"; export default { name: &#39;app&#39;, data () { return { msg: &#39;Welcome to Your Vue.js App&#39; } }, computed:{ ...mapGetters({ todoCount:"nCounts" }) }, components:{ todoInput, todoList } } </script>

index.html添加bootstrap.css

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>vue-vuex-demo</title>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  </head>
  <body>
    <p id="app"></p>
    <script src="/dist/build.js"></script>
  </body>
</html>

以上就是本篇文章的所有内容,大家要是还不太了解的话,可以自己多实现两边就很容易掌握了哦!

相关推荐:

Vuejs搜索匹配功能实例详解

Vuejs2.0子组件调用父组件的方法

The above is the detailed content of Detailed explanation of plug-in status management implemented in vuejs. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn