vue-7-1 vuex
vue: vue-router, vuex
vuex
作用:用来给vue做状态管理,类似于保存公共变量,等数据
一般是用来存储 用户登录状态,头像,用户名,地理位置等,也可以用来保存商品的“收藏”, “购物车”的物品等
安装:
npm install vuex --save
或
npm install vuex@版本(3,4)--save 根据vue的版本来安装
使用:
类似于vue-router
1. 创建文件夹,一般叫做store
2. 创建index.js
3. 导入Vuex,添加到vue中,并在入口文件main.js中导入store, 添加到
import Vuex from 'vuex' import Vue from 'vue' Vue.use(Vuex) const store = new Vuex.Store({ state:{ }, mutations:{ }, actions:{ }, getters:{ }, modules:{ } }) export default store
import Vue from 'vue' import App from './App.vue' import router from "./router"; import store from "./store"; Vue.config.productionTip = false new Vue({ render: h => h(App), router, store }).$mount('#app')
4. 在vuex的store对象中的各属性中,增加数据,如state中增加count:1000
5. 使用(错误使用)
$store.state.count
6. 正确使用(按照vuex的使用规范),如多个组件都引用了改count,而如果几个组件都有修改count的操作,那么谁操作了改count就需要有记录,按照规范修改vuex的值,就可以使用vuex的一个浏览器插件Devtools来管理记录
1. 修改vuex中值的规范(异步操作时): 组件调用vuex中state中的值,通过vuex中的Actions(行动)传给 Mutations(变化) 再进行操作,这时就可以通过Devtools插件来管理记录
2. 只包含同步操作时:可以跳过Actions,直接通过Mutations来修改state的值
异步:如向后端发送网络请求时,Backend API (访问后端的接口)
正确使用过程:
1. 安装浏览器插件:devtools
2. 重启浏览器
3. 访问vue, F12打开 控制台 -->网络右侧的“ 》”,点击Vue

4. 通过点击下图按钮,可以查看组件,路由,vuex的相关信息,点击Vuex

5. 通过mutations修改state的值,先在store的index.js中定义好mutations中的操作
state:{ count: 1000, name: 'leaf' }, mutations:{ addition(state){ state.count++ }, subtraction(state){ state.count-- } },
6. 再在组件中通过事件监听来调用mutations的方法
<template>
<div id="app">
<button @click="add">+</button>
<h2>{{$store.state.count}}</h2>
<button @click="sub">-</button>
</div>
</template>
<script>
export default {
name: 'App',
methods:{
add(){
this.$store.commit('addition')
},
sub(){
this.$store.commit('subtraction')
}
}
}
</script>

浙公网安备 33010602011771号