Vuex状态管理

单界面的状态管理

State:状态。(你姑且可以当做就是data中的属性)
View:视图层,可以针对State的变化,显示不同的信息。(这个好理解吧?)
Actions:这里的Actions主要是用户的各种操作:点击、输入等等,会导致状态的改变

官方看图

View->Actions->State->View

多界面的状态管理

官方看图

创建使用
需求: 一个数字, 二个按钮, 加减

需要在某个地方存放我们的Vuex代码, 先创建一个文件夹store,并且在其中创建一个index.js文件
在index.js文件中写入如下代码
import Vue from 'Vue'
import Vuex from 'Vuex'

Vue.use(Vuex)

const store = new Vuex.store({
state: {
count: 0
},
mutations: {
// state是默认的参数
increment(state) {
state.count++
},
decrement(state) {
state.count--
}
}
})

export default store

挂载到Vue实例中, 让所有的Vue组件都可以使用这个store对象 - 来到main.js文件,导入store对象,并且放在new Vue中, 这样在其他Vue组件中,我们就可以通过this.$store的方式,获取到这个store对象了
import Vue from 'vue'
import App from './App'
impotr store from './store'

new Vue({
e;: '#app',
stroe,
render: h => h(App)
})

使用Vuex的count
<template>
<dov id="app">
<p>{{count}}</p>
<button @click="increment">+1</button>
<button @click="decrement">-1</button>
</div>
</template>

<script>
export default {
name: 'App',
computed: {
count: function () {
return this.$store.state.count
}
},
methods: {
increment: function 90 {
this.$store.commit('increment');
},
decrement: function 90 {
this.$store.commit('decrement');
}
}
}
</script>

总结
通过this.$store.state.属性的方式来访问状态
通过this.$store.commit(‘mutation中方法’)来修改状态

posted @   PanTi  阅读(42)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示