vue五十三:vuex的使用

Vuex
Vuex是在中大型项目中,用来管理一些变量的。因为如果项目比较大,一些数据在各个页面中可能需要进行交替使用,如果数据量比较大,通过params或者query的方式不太方便。这时候就可以使用Vuex来管理这些数据。

官方文档:https://vuex.vuejs.org/zh/guide/

安装:
通过script安装:<script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>。
通过npm安装:npm install vuex --save。
如果是通过模块化打包的形式使用vuex,则在使用之前需要先通过Vue.use(Vuex)来安装:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

vuex默认依赖Promise,如果使用的浏览器并没有实现 Promise (比如 IE),那么可以使用es6-promise。
可以通过 CDN 将其引入:
<script src="https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.auto.js"></script>
或者通过npm install es6-promise --save。
如果是用模块化打包的形式使用,那么还需要导入一下:
import 'es6-promise/auto'

基本使用:
每一个Vuex应用的核心就是store(仓库)。store可以理解为就是一个容器,它包含着你的应用中大部分的状态(state)(就是变量)。Vuex和单纯的全局对象有以下两点不同:

1.Vuex的状态存储是响应式的。当Vue组件从store中读取状态的时候,若store中的状态发生变化,那么相应的组件也会相应地得到高效更新。
2.不能直接改变store中的状态。改变store中的状态的唯一途径就是显式地提交 (commit) mutation。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够实现一些工具帮助我们更好地了解我们的应用。

import Vue from "vue"
import Vuex from "vuex"

Vue.use(Vuex);

const store = new Vuex.Store({
state: {
count: 0
}
})

export default store

import Vue from 'vue'
import App from './App.vue'
import store from "./store";

Vue.config.productionTip = false;

new Vue({
render: h => h(App),
store // 使用store
}).$mount('#app');

使用

<template>
<div id="app">
<h1>{{$store.state.count}}</h1>
</div>
</template>

<script>

export default {
name: 'App',
mounted() {
console.log('store: ', this.$store.state.count);
},
components: {}
}
</script>

<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>

修改

方式一直接修改(不推荐):

<template>
<div id="app">
<h1>{{$store.state.count}}</h1>
<button @click="$store.state.count++">增加</button>
<button @click="$store.state.count--">减少</button>
</div>
</template>

方式二:封装函数

在mutations中封装函数,使用commit("函数名")调用

getter:
有时候我们需要从store中的state中派生出一些状态,例如对列表进行过滤并计数:

## 安装:
1. npm install vuex --save
2. 如果你的网站想要支持那些不支持Promise的浏览器:npm install es6-promise --save

## 使用:
1. Vue.use(Vuex)
2. 创建Store对象:
const store = new Vuex.Store({
state: {
count: 10
},
mutations: {
increment(state){
state.count++
},
substract(state){
state.count--
}
},
getters: {
currentCount(state){
return "当前的count为:"+state.count
}
}
})
3. 在main.js中,需要把store放到`Vue`对象中,这样以后在其他的组件中才能通过`this.$store`的方式方便的访问到。

## 数据的操作:
1. 如果是直接获取,那么可以通过`this.$store.state.xxx`来访问。
2. 如果想要修改,那么建议通过`mutation`的形式来操作。可以在`Store`中定义一些`mutations`。
3. 以后调用的时候,需要用`$store.commit("mutation 名称")`来调用。
4. getters:非常类似于组件中的计算属性,可以进行一些操作再把值给返回回去。在组件中调用是通过`$store.getters.xxx`来调用。
讨论群:249728408
原文地址:https://www.cnblogs.com/zhongyehai/p/12555874.html