Vue 中 store 模式的基本用法 您所在的位置:网站首页 shop与shopping的用法 Vue 中 store 模式的基本用法

Vue 中 store 模式的基本用法

2024-07-04 20:57| 来源: 网络整理| 查看: 265

前言

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

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

Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。

你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够实现一些工具帮助我们更好地了解我们的应用。

store 的核心概念 State

state 表示了 store 中的状态,类似于 vue 实例中的 data 属性。

Mutation

更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。

Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数

Action

Action 类似于 mutation,不同在于:

Action 提交的是 mutation,而不是直接变更状态。

Action 可以包含任意异步操作。

一个示例 const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment (state) { state.count++ } }, actions: { increment (context) { context.commit('increment') } } }) store 的用法

使用 store 之前, 先要安装 vuex :

npm install vuex

安装 Vuex 之后,让我们来创建一个 store。创建过程直截了当——仅需要提供一个初始 state 对象和一些 mutation。

新建 store 文件夹,再新建 index.js 文件:

import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { count: 0 }, mutations: { increment(state){ state.count++; } } })

为了在 Vue 组件中访问 this.$store property,你需要为 Vue 实例提供创建好的 store。Vuex 提供了一个从根组件向所有子组件,以 store 选项的方式“注入”该 store 的机制。

也就是在 main.js 文件中导入,并注册到 vue 根实例中:

import store from './store' ... new Vue({ el: "#app", store: store, ...

然后就可以在任意一个 vue 组件的 methods 方法属性下通过 store.commit('increment')来调用:

... methods:{ increment:function(){ this.$store.commit("increment"); console.log(this.$store.state.count); }, ...

效果如下:

每次点击,count 就会 +1.

参考资源

https://vuex.vuejs.org/zh/

https://segmentfault.com/a/1190000023564695?utm_source=tag-newest

https://www.jianshu.com/p/eb23c72ab02a

每天学习一点点,每天进步一点点。



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有