current position:Home>Vue - 14 vuex installs the use of state, movements, and getters

Vue - 14 vuex installs the use of state, movements, and getters

2022-01-27 01:26:35 Nanchen_ forty-two

Catalog

Vuex What is it? ?

One 、 You can use it directly vue-ui Download plug-ins vuex

Two 、 Use npm install vuex

3、 ... and 、yarn install

vuex The five cores of

mapState Auxiliary function

mapMutations Auxiliary function

load

mapGetters Auxiliary function


Vuex What is it? ?

Introduce :Vuex Is a special for Vue.js State management mode of application development .

understand : The core is  store( Warehouse ), What is the warehouse for ? You think it's used to store things .

Look at an official website picture :

state: Store data and status .

mutatins: Popular understanding mutations, It contains a collection of methods to change data , This is a Veux One important thing about design , Is to put all the logical methods of processing data in mutations Inside , Separate data from view . Bear in mind :Vuex in store The only way to change the data is mutation!

action: stay mutation We talked about ,mutation Is a collection of methods for storing and processing data , When we use it, we need commit. however commit It's a synchronization function , And it can only be executed synchronously . What do we want to do with asynchronous operations ?
effect : stay actions Submitted in mutation, And can contain any asynchronous operation .actions It can be understood that by mutations The method of data inside becomes the asynchronous method of data processing , In short, asynchronous operation of data ( But still through mutation To operate , Because only it can operate )

  Let's talk about the specific installation method

But first you have to have a scaffold , For the specific installation method, please refer to Vue—— install @vue/cli(Vue The scaffold ) In three ways

One 、 You can use it directly vue-ui Download plug-ins vuex

 

 

After installation, you will find that there is one more in the file store Folder , There's a index.js file  

 

store/index.js There should be the following code in :

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
  state: {
  },
  mutations:{
  },
  getter:{
  },
  actions: {
  },
  modules: {
  }
})

  The next in main.js Configuration is introduced in

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store';
Vue.config.productionTip = false

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

  Once introduced, you can use vuex 了


Two 、 Use npm install vuex

npm install vuex --save

3、 ... and 、yarn install

yarn add vuex

After installation It doesn't generate automatically store Folders and files inside , At this time, you should create and write the configuration items in it

Sure package.json Check to see if the installation is successful vuex


So let's see vuex The five cores of :

vuex The five cores of

That is to say store Under folder index.js Five states in

state、mutaions、getter、actions、modules

1.、state:vuex The basic data of , Used to store variables

stay vue Use in  

$store.state.(state The name of the data in )  

state The method is to write in the calculation attribute (computed) Inside

2、mutation: Method of submitting updated data , It has to be synchronized ( If you need to use asynchronously action). Every mutation All have a string Event type (type) and One Callback function (handler).

stay vue Use in

$store.commit('')

mutation The way is to write it in methods Inside

3、 geeter: From the basic data (state) Derived data , amount to state Calculated attributes of , Methods with return values

We can argue that ,【getters】 yes store Calculated attributes of .getters The method is to write in the calculation attribute (computed) Inside

4. action: and mutation The functions of are roughly the same , The difference is  Action Is submitted mutation, Instead of changing the state directly . Action You can include any asynchronous operation .

5. modules: modularization vuex, Each module can have its own state、mutation、action、getters, Make the structure very clear , Easy to manage .
Simply put, you can put the above state、mutation、action、getters Integrate into one user.js, Then put store.js Inside .


Use state Four ways to display data

index. part

  state: {
    count:5
  },

app.vue part   as follows :

The first one is :

<h1>{
   { $store.state.count }}</h1>

The second kind :

 <h2>{
   { vcount }}</h2>
 computed: {
			vcount() {
				return this.$store.state.count
			}
		} 

The third kind of : 

<h3>{
   { count }}</h3>

mapState Auxiliary function

When a component needs to get multiple states , It's a bit repetitive and redundant to declare these states as calculated properties . To solve this problem , We can use mapState Auxiliary functions help us to generate calculated properties , Let you press the key a few times less .

Next, the auxiliary function is introduced :

import { mapState} from "vuex";
computed:{
    ...mapState(["count"]),
}

A fourth :

<h4>{
   { count }}</h4>
computed:{
    ...mapState({
      count: (state) => state.count,
    }),
}

The effect is as follows :

  Use mutation Write out the addition and subtraction counter

index.js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
  state: {
    count:5
  },
  mutations: {
    add(state){
      state.count++
    },
    sub(state){
      state.count--
    }
  },
})

app.vue part   as follows :

The first one is :

    <h1>{
   { $store.state.count }}</h1>
    <button @click="vadd">+</button>
    <button @click="vsub">-</button>
methods:{
    vadd() {
      this.$store.commit("add");
    },
    vsub() {
      this.$store.commit("sub");
    },
}

The second kind :

    <h2>{
   { vcount }}</h2>
    <button @click="$store.commit('add')">+</button>
    <button @click="$store.commit('sub')">-</button>
  computed: {
    vcount() {
      return this.$store.state.count;
    },
}

The third kind of :

    <h3>{
   { count }}</h3>
    <button @click="add">+</button>
    <button @click="sub">-</button>

mapMutations Auxiliary function

Similar to other auxiliary functions , You can use it in components this.$store.commit(‘xxx’) Submit mutation, Or use mapMutations Auxiliary function will methods It maps to store.commit call ( You need to inject store)

Introduce auxiliary functions : mapMutations 

import { mapState ,mapMutations } from "vuex";
methods:{
    ...mapMutations(['add', 'sub'])
}

A fourth :

    <h4>{
   { count }}</h4>
    <button @click="sadd">+</button>
    <button @click="ssub">-</button>
methods:{
    ...mapMutations({
      sadd: "add",
      ssub: "sub",
    }),
}

The fifth 01  Click to increase 5 perhaps 10 Even other values   By reference

    //index.js part 
		inc(state,n){
			console.log(n);
			state.count += n
		},

app.vue part  

<button @click="inc(5)">+5</button>
<button @click="inc(10)">+10</button>
methods:{
    ...mapMutations(['inc'])
}

You can also write like this :

<button @click="Inc2(5)">+5</button>
<button @click="Inc2(10)">+10</button>
methods:{
    ...mapMutations({
      Inc2: "inc",
    }),
}

6 kinds of adopt preload Load form

mutations The load of

Pass the value to Mutations   to store.commit Pass an additional parameter , It's called mutation The load of

index.js part :

    // index.js  part 
    //  The second parameter is the mode of loading , Like an object , An array , String, etc 
		incrementcount(state,preload){
			console.log(preload);
			state.count += preload.count
		}

app.vue part  

<h2>{
   {count}}</h2>
<button @click="counter(5)">+5</button>
<button @click="counter(10)">+10</button>
 counter(count) {
				this.$store.commit({
					type: 'incrementcount',
					count
				})
			} 

The display effect is as follows :

  Two ways to add objects to an array : 

// index.js part 
export default new Vuex.Store({
  state: {
    record:[
			{id:100,name:'Nanchen',age:23},
			{id:101,name:'JiuAn',age:30},
			{id:102,name:'NanXi',age:50},
			{id:103,name:'QiuYun',age:28},
		]
  },
mutations:{
    add(state,preload){
			state.record.push(preload)
		}
}

app.vue part   

    <p>{
   { record }}</p>
    <button @click="add(home)"> Add a group </button>
  data() {
    return {
      home:{
        id:250,
        name:'Nanchen66',
        age:80
      },
    };
}
 methods: {
    ...mapMutations(['add']) ,
  },
  computed: {
    ...mapState(['record']),
  },

The second way :

app.vue part   

        //index.js
  mutations: {
    addrecord(state,preload){
			state.record.push(preload)
		}
  },
<h3>{
   {record}}</h3>
<button @click="sadd()"> add to +</button>
  methods: {
    sadd() {
				const home = {
					id: 114,
					name: 'xuqi',
					age: 35
				}
				this.$store.commit('addrecord',home)
			}
  },
  computed: {
    ...mapState(['record']),
  },

The effect is as follows :

 

getters

index.js

Make a new copy of the array in the object

            list: [{
				id: 1,
				name: " Commodity one ",
				status: false
			},
			{
				id: 2,
				name: " Commodity II ",
				status: true
			},
			{
				id: 3,
				name: " Commodity 3 ",
				status: false
			},
			{
				id: 4,
				name: " Commodity IV ",
				status: true
			},
			{
				id: 5,
				name: " Commodity V ",
				status: false
			}
		]
getters:{

    activeList(state){
      return state.record.filter(v=>{
        return v.status
      })
    },
  },

Here, we need to filter out those with status The value is true The object of  

app.vue part   

The first way to write it :

  <h1>{
   {$store.getters.activeList}}</h1>

The second way :

<h2>{
   {list}}</h2>
computed:{
    list(){
      return this.$store.getters.activeList
    },
}

The third way :

Using auxiliary functions mapGetters

mapGetters Auxiliary function

mapGetters  Auxiliary functions are just store Medium getter Map to local calculated properties

app.vue part   

import {mapGetters } from "vuex";
  <!--  The third method uses auxiliary functions  -->
  <h3>{
   {activeList}}</h3>
computed:{
    ...mapGetters(['activeList']),
}

The fourth way of writing :

  <!--  The fourth method  -->
  <h4>{
   {list}}</h4>
computed:{
   ...mapGetters({
      list:'activeList'
    })
}

The effect is as follows :( Remember to comment out the previous so as not to be disturbed )

  Here's the filter ID Greater than 3 The data of ( Because of the influence of the above code, it will only execute status by true also ID Greater than 3 The data of )

index.js part  

getters:{
    getList:(state,getters)=>{
      return getters.activeList.filter(v=>{
        return v.id >3
      })
    }
}

app.vue part   

 <h4>{
   {getList}}</h4>

Write directly after the fourth method :

getList:'getList'

The operation results are as follows :

Screening only needs ID by 3 The data of

index.js part   

getters:{
    getById:function(state){
      return function(id){
        return state.list.filter(function(v){
          return v.id === id
        })
      }
    }
}

app.vue part   

<h4>{
   {getById(3)}}</h4>

  After the fourth method, write :

 getById:'getById'

The effect is as follows :

copyright notice
author[Nanchen_ forty-two],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201270126324834.html

Random recommended