一,状态管理Vuex
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

Vuex的核心:state、mutations、actions
state:存储公共的一些数据
mutations:定义一些方法来修改state中的数据,数据怎么改变
actions: 使用异步的方式来触发mutations中的方法进行提交。
此部分的代码我们在vue-cli中使用
二,state状态
声明
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count:11
},
mutations: {
},
actions: {
}
})
使用
// 直接在模板中使用
<template>
<div>
vuex中的状态数据count:{
{
$store.state.count }}
</div>
</template>
// 在方法中使用
ceshi(){
console.log("Vuex中的状态数据count:",this.$store.state.count);
this.$router.push({
path:"/ceshi"
},()=>{
},()=>{
})
}

在计算属性中使用
当一个组件需要获取多个状态的时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性,让你少按几次键。
// 在组件中导入mapState函数。mapState函数返回的是一个对象
import {
mapState} from 'vuex'
// 在组件中导入mapState函数。mapState函数返回的是一个对象
<template>
<div id="app">
<div id="nav">
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>|
<el-button @click="gouwucheclick">购物车</el-button>
<el-button @click="ceshi">测试</el-button>
<br>
vuex中的状态数据count:{
{
$store.state.count }}
<br>{
{
count }}
<br> doubleCount:{
{
doubleCount }}
</div>
<router-view/>
</div>
</template>
<script>
import {
mapState} from 'vuex'
export default{
data(){
return{
baseCount:10
}
},
methods:{
gouwucheclick(){
this.$router.push({
path:"/gouwuche"
},()=>{
},()=>{
})
},
ceshi(){
console.log("Vuex中的状态数据count:",this.$store.state.count);
this.$router.push({
path:"/ceshi"
},()=>{
},()=>{
})
}
},
computed:mapState({
count:'count',
doubleCount(state){
return state.count * 2 + this.baseCount
}
})
}
</script>

使用展开运算符
在之前的示例中,不方便和本地的计算属性混合使用,下面我们使用展开运算符,这样就可以和本地的计算属性一起使用。
<template>
<div id="app">
<div id="nav">
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>|
<el-button @click="gouwucheclick">购物车</el-button>
<el-button @click="ceshi">测试</el-button>
<br>本地的计算属性{
{
localCount }}
<br>
vuex中的状态数据count:{
{
$store.state.count }}
<br>{
{
count }}
<br> doubleCount:{
{
doubleCount }}
</div>
<router-view/>
</div>
</template>
<script>
import {
mapState} from 'vuex'
export default{
data(){
return{
baseCount:10
}
},
methods:{
gouwucheclick(){
this.$router.push({
path:"/gouwuche"
},()=>{
},()=>{
})
},
ceshi(){
this.baseCount

543

被折叠的 条评论
为什么被折叠?



