zl程序教程

您现在的位置是:首页 >  其他

当前栏目

Vuex使用教程(直接上代码)

教程代码 直接 Vuex 使用
2023-09-11 14:16:33 时间

一.vuex简介

vuex是使用vue中必不可少的一部分,基于父子、兄弟组件,我们传值可能会很方便,但是如果是没有关联的组件之间要使用同一组数据,就显得很无能为力,那么vuex就很好的解决了我们这种问题,它相当于一个公共仓库,保存着所有组件都能共用的数据。 Vuex是单向数据流

二.vuex的使用

vue2中,要用vuex的3版本 npm i vuex@3

vue3中,要用vuex的4版本 npm i vuex@4

1.安装vuex依赖包 npm i vuex --save-dev

2.src文件夹下新建store,store文件夹里新建index.js,index.js 写以下代码

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

Vue.use(Vuex)
// 引入modules vuex模板
import cart from './modules/cart.js'
import path from './modules/path.js'

export default new Vuex.Store({
  // 存放数据
  state: {
    str: '你好',
    arr: ['a', 'b', 'c'],
    num: 1,
  },
  // 计算属性
  getters: {
    changeArr(state) {
      return state.arr.join('=')
    }
  },
  // 存放方法的  同步操作
  mutations: {
    btn(state, chuan) {
      console.log(state.str, chuan)
    },
    add(state) {
      state.num++
    }
  },
  // 提交mutations的  可以包含任意的异步操作
  actions: {
    changeAdd({ commit }) {
      setTimeout(() => {
        commit('add')
      }, 500)
    }
  },
  // 引入modules vuex模板
  modules: {
    cart,
    path
  },
}) 

3.需要用到数据的地方:

<template>
  <div class="hello">
    <h1>{{ str }}</h1>
    <h1>{{ arr }}</h1>
    <h1>{{ changeArr }}</h1>
    <button @click="btn('传')">按钮</button>
    <hr />
    {{ num }}
    <button @click="changeAdd">mutations同步增加</button>
  </div>
</template>

<script>
import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
export default {
  name: "HelloWorld",
  // computed有缓存
  computed: {
    ...mapState(["str", "arr", "num"]),
    ...mapGetters(["changeArr"]),
  },
  methods: {
    ...mapMutations(["btn"]),
    ...mapActions(["changeAdd"]),
  },
};
</script> 

如果项目比较大,需要用到modules vuex模板

在store文件夹下新建modules文件夹,里面可以存放着:比如cart.js等

export default ({
    state: {
        cartList: "购物车管理"
    },
    getters: {},
    mutations: {},
    actions: {},
    modules: {}
})  

获取数据 

<template>
  <div class="hello">
    {{cartList}}
    {{pathList}}
  </div>
</template>

<script>
import { mapState } from "vuex";
export default {
  name: "HelloWorld", 
  computed: {
  ...mapState({
    cartList:state=>state.cart.cartList,
    pathList:state=>state.path.pathList,
  })
  }, 
};
</script> 

注意:vuex本身不是持久化存储,如需持久化存储。

1.使用localStorage自己写

2.使用vuex持久化存储插件(本质也是用的localStorage)

使用插件:

1) 安装插件 npm install --save vuex-persist

2) 在index.js中加入

import VuexPersistence from 'vuex-persist'
const vuexLocal = new VuexPersistence({
  storage: window.localStorage
})

 在modules中添加

const store = new Vuex.Store({
  state: { ... },
  mutations: { ... },
  actions: { ... },
  plugins: [vuexLocal.plugin]
})