前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >vuex使用记录

vuex使用记录

作者头像
渔父歌
发布2020-03-25 23:37:45
1.2K0
发布2020-03-25 23:37:45
举报
文章被收录于专栏:数据结构笔记数据结构笔记

副标题:vuex使用详解、vue使用全局变量、vue使用 store

这篇博客主要记录了 vuex的使用方法,简单的翻译了官方文档加上一点自己的理解。

附上官方文档的链接,想更进一步了解vuex的朋友可以看看:https://vuex.vuejs.org/

有些文章里面会把 vuex称作 store,这是因为 vuex里最常用的就是 Store类,绑定到vue环境时也是以 $store 绑定的。我们先简单了解一下这5个概念。

一、相关概念

按照官方文档的说法,vuex有5个核心概念,分别是 state、getters、mutations、actions和 modules。

state相当于只读变量,组件可以访问 state变量的值,但是不能直接对其进行修改。注意我这里说的是不能直接进行修改,不是不能修改。想要修改 state里变量的值必须要通过 mutations。

getters就是我们通常所说的 getters,在 getters里可以访问到所有的 state变量,我们可以方便的用 getters定义一些需要计算的值。

mutations用来修改 state的变量。在 mutations里定义的函数可以修改任意 state变量的值,在组件中通过 store对象的 commit方法调用相关的 mutations函数。

actions的功能和 mutations差不多,唯一的区别就是在 mutations中只支持同步的操作,而在 actions中支持异步操作(可以在组件中进行链式调用,类似 axios)。另外我们还可以在 actions中调用 mutations。在组件中通过 store对象的 dispatch方法来调用 actions里的方法。

modules有点像命名空间,将逻辑关系相近的变量和操作放到一个 module中,个人感觉一般情况用不上这个功能,感兴趣的可以看一下官方文档:https://vuex.vuejs.org/guide/modules.html

二、如何在 vue中使用 vuex

了解了相关概念之后,我们进入实战,如何在 vue项目中使用 vuex。

第一步先在项目中安装 vuex,使用下面的命令:

代码语言:javascript
复制
npm install --save vuex
或者
cnpm install --save vuex

然后创建一个 store.js文件,内容如下:

代码语言:javascript
复制
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
    },
    mutations: {
    },
    actions: {
    },
    getters: {
    }
})

我们可以把有关 vuex的代码全部放在这个文件里,但是现在我们还没有把 vuex添加到 vue的环境中,还要打开 main.js文件做一点修改:

代码语言:javascript
复制
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import store from './store'

Vue.config.productionTip = false

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

这里我们做的操作主要是 import上面创建的 store文件,然后将 store对象添加到 vue的初始化参数里。这样我们就可以在 vue的组件中通过 this.$store 来访问 store对象了。

下面我们看看怎么在组件里使用 store.

我们现在 store.js文件中定义一些 state变量

代码语言:javascript
复制
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        count: null,
    },
    mutations: {
        increase(state) {
            // count自增
            state.count++
        }
    },
    actions: {
        initCount(state) {
            console.log('init')
            // 初始化 count,模拟网络请求
            return new Promise((success, reject) => {
                // 延时5000毫秒初始化count
                setTimeout(() => {
                    state.count = 0;
                    success();
                }, 5000)
            })
        }
    },
    getters: {
        doubleCount(state) {
            // 返回2*count
            return 2 * state.count
        }
    }
})

然后创建一个 Count组件,代码如下:

代码语言:javascript
复制
// Count.vue
<template>
    <div>
        <div>count: {{count?count:'未初始化'}}</div>
        <div>doubleCount: {{count?doubleCount:'未初始化'}}</div>
    </div>
</template>

<script>
export default {
    name: 'Count',
    data(){
        return {

        }
    },
    mounted(){
        this.$store.dispatch('initCount').then(()=>{
            setInterval(()=>{
                // 每隔 1s count自增一次
                this.$store.commit('increase')
            }, 1000)
        })
    },
    computed: {
        // 使用 computed动态更新 count的值,直接放在 data中不能动态更新
        // 因为直接放在 data中的话只是一个赋值操作
        count(){
            return this.$store.state.count
        },
        doubleCount(){
            return this.$store.getters.doubleCount
        }
    }
}
</script>
代码语言:javascript
复制
// App.vue
<template>
    <div id="app">
        <Count></Count>
    </div>
</template>

<script>
import Count from "./components/Count.vue"

export default {
    name: 'app',
    components: {
        Count
    }
};
</script>

<style>
* {
    padding: 0;
    margin: 0;
}

html,
body,
#app {
    width: 100%;
    height: 100%;
    color: #2c3e50;
}

#app {
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>

运行结果:

未初始化

本文参与?腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客?前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与?腾讯云自媒体分享计划? ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、相关概念
  • 二、如何在 vue中使用 vuex
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
http://www.vxiaotou.com