zoukankan      html  css  js  c++  java
  • Vuex最简单教程

    Vuex最简单教程

    一、总结

    一句话总结:

    vuex 是一个专门为vue.js应用程序开发的状态管理模式。这个状态我们可以理解为在data中的属性,需要共享给其他组件使用的部分。也就是说,是我们需要共享的data,使用vuex进行统一集中式的管理。

    1、vuex中,默认的五种基本的对象的理解?

    state:存储状态(变量)、getters:对数据获取之前的再次编译、mutations:修改状态、actions:写方法、modules:store的子模块


    a、state:存储状态(变量)
    b、getters:对数据获取之前的再次编译,可以理解为state的计算属性。我们在组件中使用 $sotre.getters.fun()
    c、mutations:修改状态,并且是同步的。在组件中使用$store.commit('',params)。这个和我们组件中的自定义事件类似。
    d、actions:写方法,异步操作,从后台获取数据也在这里。在组件中使用是$store.dispath('')
    e、modules:store的子模块,为了开发大型项目,方便状态管理而使用的。这里我们就不解释了,用起来和上面的一样。

    2、vuex中的getters对象是干嘛的?

    getters:对数据获取之前的再次编译,可以理解为state的计算属性。我们在组件中使用 $sotre.getters.fun()

    3、vuex中的actions对象是干嘛的?

    就是行为,就是写方法,写好方法之后调用mutations进行具体状态的更新
    const actions = {
        actionsAddCount(context, n = 0) {
            console.log(context)
            return context.commit('mutationsAddCount', n)
        },
        actionsReduceCount({ commit }, n = 0) {
            return commit('mutationsReduceCount', n)
        }
    }

    4、安装vuex 命令是什么?

    npm install vuex --save

    5、初始安装好vuex之后,我们在哪个文件里面操作vuex?

    在store.js文件中
    import Vue from 'vue'
    import Vuex from 'vuex'
    
    Vue.use(Vuex)
    
    const state = {
        count: 0
    }
    
    export default new Vuex.Store({
        state
    })

    6、如何在main.js中引入store?

    在new的Vue对象中加上store即可
    import Vue from 'vue'
    import App from './App'
    import router from './router'
    import store from './vuex/store' // 引入store
    Vue.config.productionTip = false
    
    /* eslint-disable no-new */
    new Vue({
        el: '#app',
        router,
        store,
        components: { App },
        template: '<App/>'
    })

    7、最基本的使用vuex中的状态count(变量)?

    直接在模板中{{$store.state.count}},因为在main.js介绍中配置好store之后,store对象是哪里都可以使用的
    <template>
      <div class="hello">
        <h3>{{$store.state.count}}</h3>
      </div>
    </template>

    8、vuex对象中的mutations对象具体是做啥的?

    更新状态,也就是更新state中的变量的,比如加,比如减

    二、五分钟搞懂Vuex

    转自或参考:五分钟搞懂Vuex
    https://www.cnblogs.com/chinabin1993/p/9848720.html

    先说一下vuex到底是什么?

    vuex 是一个专门为vue.js应用程序开发的状态管理模式。

    这个状态我们可以理解为在data中的属性,需要共享给其他组件使用的部分。

    也就是说,是我们需要共享的data,使用vuex进行统一集中式的管理。

    vuex中,有默认的五种基本的对象:

    • state:存储状态(变量)
    • getters:对数据获取之前的再次编译,可以理解为state的计算属性。我们在组件中使用 $sotre.getters.fun()
    • mutations:修改状态,并且是同步的。在组件中使用$store.commit('',params)。这个和我们组件中的自定义事件类似。
    • actions:异步操作。在组件中使用是$store.dispath('')
    • modules:store的子模块,为了开发大型项目,方便状态管理而使用的。这里我们就不解释了,用起来和上面的一样。

    下面我们正式开始,一步步使用vuex

    1、首先创建一个vue-cli项目

    执行下面的命令,创建一个app项目(这里也可以使用其他非webpack模板,以及非app名称)

    vue init webpack app

    2、创建完成之后,我们进入文件夹下,并且运行项目

    cd app/
    npm run dev

    接下来我们在src目录下创建一个vuex文件夹

    并在vuex文件夹下创建一个store.js文件

    文件夹目录长得是这个样子

    3、目前我们还没有引入vuex,我们需要先下载vuex,并且引入它

    在保证我们处于我们项目下,在命令行输入下面命令,安装vuex

    npm install vuex --save

    4、安装成功之后,我们就可以在store.js中尽情玩耍我们的vuex了!

    在store.js文件中,引入vuex并且使用vuex,这里注意我的变量名是大写Vue和Vuex 

    import Vue from 'vue'
    import Vuex from 'vuex'
    
    Vue.use(Vuex)
    
    const state = {
        count: 0
    }
    
    export default new Vuex.Store({
        state
    })

    接下来,在main.js中引入store

    import Vue from 'vue'
    import App from './App'
    import router from './router'
    import store from './vuex/store' // 引入store
    Vue.config.productionTip = false
    
    /* eslint-disable no-new */
    new Vue({
        el: '#app',
        router,
        store,
        components: { App },
        template: '<App/>'
    })

    然我我们在任意一个组件中就可以使用我们定义的count属性了。

    这里我们在helloWorld中使用一下,去除helloworld.vue中不用的标签

    <template>
      <div class="hello">
        <h3>{{$store.state.count}}</h3>
      </div>
    </template>

    打开我们刚才运行项目的浏览器,可以看到已经使用成功了!

    并且在vue开发工具中我们可以看到我们定义的变量count

    到这一步,已经成功了一小半!vuex很简单吧?

    回想一下,我们只需要在下载安装使用vuex,在我们定义的store.js中定义state对象,并且暴露出去。

    在main.js中使用我们的store.js(这里是为了防止在各个组件中引用,因为main.js中,有我们的new Vue 实例啊!)

    现在我们已经使用了vuex中的state,接下来我们如何操作这个值呢? 没错!用mutations和actions

    我们继续操作store.js文件

    我们在sotre.js中定义mutations对象,该对象中有两个方法,mutations里面的参数,第一个默认为state,接下来的为自定义参数。

    我们在mutations中定义两个方法,增加和减少,并且设置一个参数n,默认值为0,然后在Vuex.Store中使用它

    /**
     * mutations 里面放置的是我们操作state对象属性的方法
     */
    const mutations = {
        mutationsAddCount(state, n = 0) {
            return (state.count += n)
        },
        mutationsReduceCount(state, n = 0) {
            return (state.count -= n)
        }
    }
    export default new Vuex.Store({
        state,
        mutations
    })

    然后我们在helloWorld.vue中,使用这个方法

    还记得我们如何在组件中使用mutations吗?就和自定义事件非常相似

    <template>
      <div class="hello">
        <h3>{{$store.state.count}}</h3>
        <div>
          <button @click="handleAddClick(10)">增加</button>
          <button @click="handleReduceClick(10)">减少</button>
        </div>
      </div>
    </template>
    methods: {
        handleAddClick(n){
          this.$store.commit('mutationsAddCount',n);
        },
        handleReduceClick(n){
          this.$store.commit('mutationsReduceCount',n);
        }
      }

    来浏览器看一下效果如何!

    我们可以看到每当触发事件时,我们都可以在vue开发工具中看到我们触发的mutations方法,以及参数

    完美!

    接下来就是actions,actions是异步操作

    创建actions对象,并且使用

    这里我在两个方法中使用了两个不同的参数,一个是context,它是一个和store对象具有相同对象属性的参数。在第二个函数中,我是直接使用了这个对象的commit的方法。

    凭大家喜好就行

    const actions = {
        actionsAddCount(context, n = 0) {
            console.log(context)
            return context.commit('mutationsAddCount', n)
        },
        actionsReduceCount({ commit }, n = 0) {
            return commit('mutationsReduceCount', n)
        }
    }
    export default new Vuex.Store({
        state,
        mutations,
        actions
    })

    在helloWorld.vue中

    在methods中,增加两个方法,使用dispath来触发

     <div>异步操作</div>
      <div>
        <button @click="handleActionsAdd(10)">异步增加</button>
        <button @click="handleActionsReduce(10)">异步减少</button>
      </div>
    handleActionsAdd(n){
          this.$store.dispatch('actionsAddCount',n)
        },
        handleActionsReduce(n){
          this.$store.dispatch('actionsReduceCount',n)
        }

    进入浏览器看下效果如何!

    最后就是getters

    我们一般使用getters来获取我们的state,因为它算是state的一个计算属性

    const getters = {
        getterCount(state, n = 0) {
            return (state.count += n)
        }
    }
    export default new Vuex.Store({
        state,
        mutations,
        actions,
        getters
    })
    <h4>{{count}}</h4>
    const getters = {
        getterCount(state) {
            return (state.count += 10)
        }
    }

    getters算是非常简单的了。

    到这里,如果全都看懂了,vuex你已经没有压力了。

    但是vuex官方给了我们一个更简单的方式来使用vuex, 也就是 {mapState, mapMutations, mapActions, mapGetters}

    只要我们把上面基础的搞懂,这些都不在话下,只是方面我们书写罢了。

    就这么简单,这里我们用到了es6的扩展运算符。如果不熟悉的同学还是去看看阮一峰大神的《Es6标准入门》这本书,我是看完了,受益匪浅!

    <script>
    import {mapState, mapMutations, mapActions, mapGetters} from 'vuex'
    export default {
      name: 'HelloWorld',
      data () {
        return {
          msg: 'Welcome to Your Vue.js App'
        }
      },
      methods: {
        ...mapMutations({
          handleAddClick: 'mutationsAddCount',
          handleReduceClick: 'mutationsReduceCount'
        }),
        ...mapActions({
          handleActionsAdd: 'actionsAddCount',
          handleActionsReduce: 'actionsReduceCount'
        })
        // handleAddClick(n){
        //   this.$store.commit('mutationsAddCount',n);
        // },
        // handleReduceClick(n){
        //   this.$store.commit('mutationsReduceCount',n);
        // },
        // handleActionsAdd(n){
        //   this.$store.dispatch('actionsAddCount',n)
        // },
        // handleActionsReduce(n){
        //   this.$store.dispatch('actionsReduceCount',n)
        // }
      },
      computed: {
        count(){
          return this.$store.getters.getterCount
        }
      }
    }
    </script>

    同理,getters和 state也可以使用 mapState,mapGetters

    如果你更懒的话,我们可以使用数组,而非对象,或者es6里面的对象简写方式

    就像这种

    最后,如果大家发现有什么问题,或者错误的地方,欢迎留言交流。

    分割线----------------------------------------------------------------------
    看到后台一些小伙伴问我用的什么编辑器,我这里用的是vscode,然后把我自己的一些配置给贴上,喜欢的话可以粘贴复制一下。

    最近的效果是这样子的~~

    字体用的是Fira Code 很好用的一种字体

    {
        "editor.fontFamily": "Fira Code",
        "editor.fontLigatures": true,
        "editor.cursorStyle": "block",
      "editor.fontSize": 16,
      "editor.lineHeight": 24,
      "editor.lineNumbers": "on",
      "editor.minimap.enabled": false,
      "editor.renderIndentGuides": false,
      "editor.rulers": [120],
      "workbench.colorTheme": "Andromeda",
      "workbench.iconTheme": "vscode-great-icons",
      "editor.detectIndentation": false,
      "editor.tabSize": 2,
      "editor.quickSuggestions": {
        "other": true,
        "comments": true,
        "strings": true
      },
      "files.associations": {
        "*.cjson": "jsonc",
        "*.wxss": "css",
        "*.wxs": "javascript"
      },
      "emmet.includeLanguages": {
        "wxml": "html"
      },
      "minapp-vscode.disableAutoConfig": true,
      "window.zoomLevel": -1,
      "[vue]": {
        "editor.defaultFormatter": "octref.vetur"
      },
      "todo-tree.defaultHighlight": {
        "type": "text",
    },
    "todo-tree.customHighlight": {
        "TODO": {
            "icon": "check",
            "foreground": "#000",
            "background": "#cecb32",
            "iconColour": "#fffc43"
        },
        "FIXME": {
            "icon": "alert",
            "foreground": "#fff",
            "background": "#ca4848",
            "iconColour": "#ff4343"
        }
    },
    "todo-tree.highlights.customHighlight": {
      "TODO": {
        "icon": "check",
        "foreground": "#000",
        "background": "#cecb32",
        "iconColour": "#fffc43"
      },
      "FIXME": {
        "icon": "alert",
        "foreground": "#fff",
        "background": "#ca4848",
        "iconColour": "#ff4343"
      }
    },
    "todo-tree.highlights.defaultHighlight": {
      "type": "text"
    }
    }
     
  • 相关阅读:
    627. Swap Salary
    176. Second Highest Salary
    596. Classes More Than 5 Students
    183. Customers Who Never Order
    181. Employees Earning More Than Their Managers
    182. Duplicate Emails
    175. Combine Two Tables
    620. Not Boring Movies
    595. Big Countries
    HDU 6034 Balala Power! (贪心+坑题)
  • 原文地址:https://www.cnblogs.com/Renyi-Fan/p/12509176.html
Copyright © 2011-2022 走看看