vuex基本使用教程

前言

vuex的具体使用教程查看官网文档 https://vuex.vuejs.org/zh/installation.html,这里只是记录一下vuex在项目中具体的使用

简单集成过程

创建vuex模块文件

  在项目的 src/ 目录下创建 【store】文件夹,并在 src/store/ 目录下创建 store.js. 这个js名称可以按自己需要更改

  

模块文件内容

  在store.js中加入如下代码  

// src/store/store.js

import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex)
let store = new Vuex.Store({
    // 1. state
    state:{
        city:"城市名",
        event:[], //存储websocket传输过来的数据
    },
    getters:{
        getEvent(state){
            return state.city;
        }
    },
    mutations:{
        setEvent(state, event){
            state.event.push(event)
        }
    },
});

export default store;

这里大概简述一下vuex.Store参数中的几个属性:

  • state: 存储变量的地方,我们平时定义的变量都放到这里面, 外部可以通过 this.$store.state.* 去获取存储的变量值
  • getters: 获取变量的时候添加的过滤器,用getter里面定义的函数去获取state数据时,可以对state里的数据提前进行加工处理
  • mutations: 定义一个函数去修改state里面的值,直接修改state里的值vue会监听不到数据变化,所以通过mutations里定义函数来操作state里的数据。只能同步处理。
  • actions:定义函数去调用mutations的,这样又加了一层的目的是为了让mutations能处理异步的请求,如果项目中对state都是同步处理,就不用加这一层

挂载到vue

  在项目入口main.js中加入如下代码

// 1. 导入到main.js中
import store from "./store/store"

...

//2. 挂载到vue对象上
new Vue({
  el: '#app',
  router,
  store,             //主要看这一行
  components: { App },
  template: '<App/>'
})

vuex基本使用

  1. js模块中调用

//===== 获取state的值=====

//直接获取方法
this.$store.state.city

//通过getters定义函数获取
//这里可以传入参数,但是由于getters定义函数时第一个参数必须是state,所以这里传入的参数在getters里从第二个开始算起。(我也不知道怎么说,看文档去吧)
this.$store.getters.getEvent()


//===== 设置state的值=====

this.$store.commit("setEvent", eventDate)

  2.  html中调用

  去掉this,剩下的和js里使用一样, 例如: {{ $store.store.state.event }}

处理

原文地址:https://www.cnblogs.com/xuange306/p/12574961.html