东莞市建设局网站6,wordpress置顶排序,网站的空间什么意思,软件下载网站地址1.是什么
Vuex 是一个 Vue 的 状态管理工具#xff0c;状态就是数据。
大白话#xff1a;Vuex 是一个插件#xff0c;可以帮我们管理 Vue 通用的数据 (多组件共享的数据)。例如#xff1a;购物车数据 个人信息数
2 .核心概念 - state 状态
State提供唯一的公共数据源状态就是数据。
大白话Vuex 是一个插件可以帮我们管理 Vue 通用的数据 (多组件共享的数据)。例如购物车数据 个人信息数
2 .核心概念 - state 状态
State提供唯一的公共数据源所有共享的数据都要统一放到Store中的State中存储。
打开项目中的store.js文件在state对象中可以添加我们要共享的数据。
const store new Vuex.Store({// state 状态, 即数据, 类似于vue组件中的data,// 区别// 1.data 是组件自己的数据, // 2.state 中的数据整个vue项目的组件都能访问到state: {count: 101}
})
如何获得state里的共享数据
获取 store 1.Vue模板中获取 this.$store 2.js文件中获取 import 导入 store 模板中 {{ $store.state.xxx }} 组件逻辑中 this.$store.state.xxx JS模块中 store.state.xxx
示例
这是模版中获取
h1state的数据 - {{ $store.state.count }}/h1
组件逻辑 也就是 script
// 把state中数据定义在组件内的计算属性中computed: {count () {return this.$store.state.count}}
js模块 也就是main.js文件等等
//main.jsimport store from /storeconsole.log(store.state.count) 通过辅助函数 mapState获取 state中的数据 需要导入 import { mapState } from vuex 采用数组的形式
mapState([count]) 等价于
count () { return this.$store.state.count }
最终写法是 computed: {...mapState([count])}
这样的好处是不需要写 this.$store.state
只需要写 count 即可 其它同理
3 .核心概念 - mutations 状态
作用主要是用来修改共享数据的 所有的修改共享数据都应该在这里面写
const store new Vuex.Store({state: {count: 0},// 定义mutationsmutations: {}
})
格式说明
mutations: {// 方法里参数 第一个参数是当前store的state属性// payload 载荷 运输参数 调用mutaiions的时候 可以传递参数 传递载荷addCount (state) {state.count 1}}, 其它组件想要修改共享数据 最好使用
commit 里面的参数就是 mutations 里面的 函数名称
this.$store.commit(addCount)
当然因为它是函数所以也可以传参
注意提交的参数只能是一个, 如果有多个参数要传, 可以传递一个对象
辅助函数- mapMutations mapMutations和mapState很像它把位于mutations中的方法提取了出来我们可以将它导入 import { mapMutations } from vuex
methods: {...mapMutations([addCount])
} 上面代码的含义是将mutations的方法导入了methods中等价于 methods: {// commit(方法名, 载荷参数)addCount () {this.$store.commit(addCount)}}
此时就可以直接通过this.addCount调用了 4.使用步骤快速入门
2.1 首先要安装vuex
如果是vue2 就安装 vuex 3 vue3 就安装 vuex4
cnpm install vuex
2.2 创建一个空仓库 并导入到main.js
state 里面存的是共享数据
import {createStore} from vuex;const store createStore({state: {// 定义你的状态},mutations: {// 定义你的 mutations},actions: {// 定义你的 actions},getters: {// 定义你的 getters}});export default store; import { createApp } from vue
import { createRouter,createWebHistory } from vue-router; // 导入 createRouter 和 createWebHistory
import ElementPlus from element-plus
import element-plus/dist/index.css
import App from ./App.vue
import store from /store/index.jsconst router createRouter({history: createWebHistory(),routes: [/* your routes */]});const app createApp(App)app.use(router)
app.use(ElementPlus, { size: small, zIndex: 3000 })
app.use(store)
app.mount(#app)2.3