Home >Web Front-end >Vue.js >How to install vue state management Vuex

How to install vue state management Vuex

青灯夜游
青灯夜游Original
2021-10-27 17:18:392328browse

How to install vue state management: 1. Create a Vue-based project and execute the "npm install" command to install the dependencies; 2. In the control command line, execute the "npm install vuex --save" command to install Just Vuex.

How to install vue state management Vuex

The operating environment of this tutorial: windows7 system, vue2.9.6 version, DELL G3 computer.

1. What is Vuex

Vuex is a state management model developed specifically for Vue.js applications. It uses centralized storage to manage the state of all components of the application, and uses corresponding rules to ensure that the state changes in a predictable way. Vuex is also integrated into Vue's official debugging tool devtools extension, providing advanced debugging functions such as zero-configuration time-travel debugging, status snapshot import and export, etc.

This state self-management application includes the following parts:

  • state, the data source that drives the application;
  • view , declaratively maps state to views;
  • actions, responds to state changes caused by user input on view .

The following is a minimalist representation of the concept of "one-way data flow":

How to install vue state management Vuex

##More complex situations

    Multiple views depend on the same state.
  • Behaviors from different views need to change the same state.

How to install vue state management Vuex

2. Under what circumstances should I use Vuex?

Although Vuex can help us manage shared state, it also comes with more concepts and frameworks. This requires weighing short- and long-term benefits.

If you don't plan to develop a large single-page application, using Vuex may 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 what you need. However, if you need to build a medium to large single page application, you will most likely be thinking about how to better manage state outside the component, and Vuex will be a natural choice. To quote Redux author Dan Abramov:

Flux architecture is like glasses: you know when you need it.

3. Installation

First you need to create a Vue-based project, usually you can do this:

# 全局安装 vue-cli
$ npm install --global vue-cli
# 创建一个基于 webpack 模板的新项目
$ vue init webpack my-project
# 安装依赖,走你
$ cd my-project
$ npm install
$ npm run dev

Use npm package management tool to install vuex. Just enter the following command in the control command line.

npm install vuex --save

It should be noted that –save must be added here, because we will use your package in the production environment.

Through a simple dependency installation operation, even if vuex is successfully referenced, we can then have fun playing.

A simple example, enter the following code in the main.js file:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  }
})
store.commit('increment')

/* eslint-disable no-new */
new Vue({
  el: '#app',
  template: `<p>{{ count }}</p>`,
  computed: {
    count () {
      return store.state.count
    }
  }
})

After running, you can see a 1 displayed on the page, that is, the function increment has been executed correctly, and the count is from the initial The output of 0 becomes 1 after increment.

It should be pointed out that we submit mutation instead of directly changing store.state.count because we want to track the state changes more clearly.

Usually we don’t use it like this. A better way to use it is:

1. Create a new store folder (this is not necessary) and create a new store under the folder. js file, import our vue and vuex into the file.

import Vue from &#39;vue&#39;;
import Vuex from &#39;vuex&#39;;

2. In the store.js file, use Vue.use to reference vuex.

Vue.use(Vuex);

3. Introduce the new vuex file into main.js

import store from &#39;./store/store&#39;

4. Vuex provides a mechanism to "inject" state from the root component to each child through the store option. In the component (Vue.use(Vuex) needs to be called, by registering the store option in the root instance, the store instance will be injected into all sub-components under the root component, and the sub-components can be accessed through this.$store.:

import Vue from 'vue'
import App from './App'
import router from './router'
import store from &#39;./store/store&#39;

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  template: '',
  components: { App }
})

4. Use

1. Now add a constant object to our store.js file.

state: {
  count: 1
},

2. Use export default to encapsulate the code. Allow external reference.

export default new Vuex.Store({
  name: &#39;store&#39;,
  state: {
    count: 1
  }
})

3. Create a new Vue test template. The location is in the components folder and the name is random. I call it

count.vue. In the template we use {{$store.state.count}}Output the value of count (note: since the store has been injected into the vue instance before, there is no need to reference it again).

 <template>
    <p>
        <h2>{{msg}}</h2>
        <hr/>
        <h3>{{$store.state.count}}</h3>
    </p>
</template>
<script>
export default {
  data () {
    return {
      msg: &#39;Hello Vuex&#39;
    }
  },
  computed: {
    count () {
      return this.$store.state.count
    }
  }
}
</script>

4 , Add two methods to change state in the store.js file.

mutations: {
    increment (state) {
      state.count += 1
    },
    decrement (state) {
      state.count -= 1
    }
  }

5. Add two buttons to the test.vue template, and call the methods in mutations.

<p>
   <button @click="$store.commit(&#39;increment&#39;)">+</button>
   <button @click="$store.commit(&#39;decrement&#39;)">-</button>
</p>

6 , reference the file in index.js under the router folder, define the corresponding route, run the program and enter the interface, click the button to see the effect

{
   path: &#39;/count&#39;,
   name: &#39;Count&#39;,
   component: Count
}

五、state访问状态对象

state,这个就是我们说的访问状态对象,它就是我们SPA(单页应用程序)中的共享值。

访问状态对象赋值给内部对象,也就是把stroe.js中的值,赋值给我们模板里data中的值。有三种赋值方式

1、通过computed的计算属性直接赋值

computed属性可以在输出前,对data中的值进行改变,我们就利用这种特性把store.js中的state值赋值给我们模板中的data值。

    computed:{
        count(){
            return this.$store.state.count;
        }
    }

这里需要注意的是return this.$store.state.count这一句,一定要写this,要不你会找不到$store的。这种写法很好理解,但是写起来是比较麻烦的,那我们来看看第二种写法。

2、通过mapState的对象来赋值

我们首先要用import引入mapState。

    import {mapState} from &#39;vuex&#39;

然后还在computed计算属性里写如下代码:(根据需要选用一种方法即可)

   computed: mapState({
    // 箭头函数可使代码更简练
    count: state => state.count,   // es6写法,function (state) { return state.count }

    // 传字符串参数 &#39;count&#39; 等同于 `state => state.count`
    countAlias: &#39;count&#39;,

    // 为了能够使用 `this` 获取局部状态,必须使用常规函数
    countPlusLocalState (state) {
      return state.count + this.localCount
    }
  })

3、当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组。

computed: mapState([
  // 映射 this.count 为 store.state.count
  &#39;count&#39;
])

4、还可以采用简化写法(个人比较喜欢这种写法本质上和第三种是一个意思,后面的mutations中也有类似的写法)

// 使用对象展开运算符将此对象混入到外部对象中
    ...mapState({
      num: &#39;count&#39;
    })

这个算是最简单的写法了,在实际项目开发当中也经常这样使用。

相关推荐:《vue.js教程

The above is the detailed content of How to install vue state management Vuex. 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