Vuex是做什么的?
Vue官方:状态管理工具
状态管理是什么
需要在多个组件中共享的状态、且是响应式的、一个变,全都改变。
例如一些全局要用的的状态信息:用户登录状态、用户名称、地理位置信息、购物车中商品、等等
这时候我们就需要这么一个工具来进行全局的状态管理,Vuex就是这样的一个工具。
单页面的状态管理
View–>Actions—>State
视图层(view)触发操作(action)更改状态(state)响应回视图层(view)
vuex(Vue3.2版本)
store/index.js 创建store对象并导出store
import { createStore } from 'vuex'
export default createStore({
state: {
},
mutations: {
},
actions: {
},
modules: {
}
})
main.js 引入并使用
...
import store from './store'
...
app.use(store)
多页状态管理
vuex store对象属性介绍
Vue3中获取 store 实例对象的方法
vue2 中可以通过 this.$store.xxx
的方式拿到 store 的实例对象。
vue3 中的 setup 在 beforecreate 和 created 前执行,此时 vue对象还未被创建,没有了之前的this,所以此处我们需要用到另一种方法来获取到 store 对象。
import { useStore } from 'vuex' // 引入useStore 方法
const store = useStore() // 该方法用于返回store 实例
console.log(store) // store 实例对象
1. state
存放数据的地方
state: {
count: 100,
num: 10
},
使用:使用方法大致与vue2.x中的版本相同,通过 $store.state.属性名
来获取state中的属性。
//template中
<span>{
{$store.state.count}}</span>
<span>{
{$store.state.num}}