【Vue 基础】尚品汇项目-06-vuex模块式开发

vuex是官方提供一个插件,状态管理库,集中式管理项目中组件共用的数据。

目录

一、安装

二、vuex的基本使用

三、vuex模块式开发


一、安装

安装命令:

npm install [email protected] --save

如果安装错版本,要先卸载再重新安装,卸载命令如下:

cnpm uninstall vuex --save

二、vuex的基本使用

1. 在src目录下新建一个文件夹,命名为“store”

 在该文件夹中新建文件“index.js”

 添加如下代码:

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

//需要使用插件一次
Vue.use(Vuex)


const state = {}  // 仓库存储数据的地方

const mutations = {}  // 修改state的唯一手段
const actions = {}  // 处理actions,可以书写自己的业务逻辑,也可以处理异步
const getters = {}  // 理解为计算属性,用于简化仓库数据,让组件获取仓库的数据更加方便

//对外暴露Store类的一个实例
export default new Vuex.Store({
    state,
    mutations,
    actions,
    getters
})

 2. 在main.js中注册仓库、引入仓库

 此时组件实例的身上会多一个$store属性

3.为了观察仓库的数据,这里做一个demo

首先在“store/index.js”中添加数据:

 为了显示count的值,在"src/pages/Home/index.vue"中添加如下代码:

 如果希望添加一个按钮来修改仓库中的count值,首先在"src/pages/Home/index.vue"中添加如下代码:

 然后在“src/store/index.js”中添加如下代码:

 此时我们点击按钮就可以完成+1的功能

三、vuex模块式开发

首先删除编辑demo的代码,删除后"src/pages/Home/index.vue"的代码如下:

<template>
  <div>
    <TypeNav></TypeNav>
    <ListContainer></ListContainer>
    <Recommend></Recommend>
    <Rank></Rank>
    <Like></Like>
    <Floor></Floor>
    <Floor></Floor>
    <Brand></Brand>
  </div>

</template>

<script>
//引入其余组件
import ListContainer from '@/pages/Home/ListContainer'
import Recommend from '@/pages/Home/Recommend'
import Rank from '@/pages/Home/Rank'
import Like from '@/pages/Home/Like'
import Floor from '@/pages/Home/Floor'
import Brand from '@/pages/Home/Brand'

export default {
  name: '',
  components: {
    ListContainer,
    Recommend,
    Rank,
    Like,
    Floor,
    Brand
  }
}
</script>

<style>
</style>

 “src/store/index.js”的代码如下:

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

//需要使用插件一次
Vue.use(Vuex)

//对外暴露Store类的一个实例
export default new Vuex.Store({

})

为了实现每一个小仓库的数据对应一个模块,首先在“src/store”中新建两个文件夹,命名为“home”和“search”,分别用来存储home和search模块的数据

 在这两个文件夹下新建index.js

 编辑两个index.js代码如下:

//home模块的数据仓库
const state = {}
const mutations = {}
const actions = {}
const getters = {}

export default {
    state,
    mutations,
    actions,
    getters
}
//search模块的数据仓库
const state = {}
const mutations = {}
const actions = {}
const getters = {}

export default {
    state,
    mutations,
    actions,
    getters
}

将这两个小仓库合并到大仓库中。打开“src/store/index.js”,添加如下代码:

 此时在控制台中可以看到实现了将大仓库分为小仓库进行存储

 比如home仓库有个a=1

 search仓库有个b=2

此时可以看到分模块存储的数据如下:

猜你喜欢

转载自blog.csdn.net/ChaoChao66666/article/details/130482169