首页 > 语言 > JavaScript > 正文

vuex操作state对象的实例代码

2024-05-06 15:19:42
字体:
来源:转载
供稿:网友

Vuex是什么?

VueX 是一个专门为 Vue.js 应用设计的状态管理架构,统一管理和维护各个vue组件的可变化状态(你可以理解成 vue 组件里的某些 data )。

Vue有五个核心概念,state, getters, mutations, actions, modules。

总结

state => 基本数据
getters => 从基本数据派生的数据
mutations => 提交更改数据的方法,同步!
actions => 像一个装饰器,包裹mutations,使之可以异步。
modules => 模块化Vuex

State

state即Vuex中的基本数据!

单一状态树

Vuex使用单一状态树,即用一个对象就包含了全部的状态数据。state作为构造器选项,定义了所有我们需要的基本状态参数。

在Vue组件中获得Vuex属性

•我们可以通过Vue的Computed获得Vuex的state,如下:

const store = new Vuex.Store({  state: {    count:0  }})const app = new Vue({  //..  store,  computed: {    count: function(){      return this.$store.state.count    }  },  //..})

下面看下vuex操作state对象的实例代码

每当 store.state.count 变化的时候, 都会重新求取计算属性,并且触发更新相关联的 DOM。

每一个 Vuex 应用的核心就是 store(仓库)。

引用官方文档的两句话描述下vuex:

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

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

使用vuex里的状态

1,在根组件中引入store,那么子组件就可以通过this.$store.state.数据名字得到这个全局属性了。

我用的vue-cli创建的项目,App.vue就是根组件

App.vue的代码

<template> <div id="app">   <h1>{{$store.state.count}}</h1>    <router-view/> </div></template><script> import store from '@/vuex/store';export default { name: 'App', store}</script><style></style>

在component文件夹下Count.vue代码

<template> <div>   <h3>{{this.$store.state.count}}</h3> </div></template><script>   export default {    name:'count',  }</script><style scoped></style>

store.js的代码

import Vue from 'vue'import Vuex from 'vuex'Vue.use(Vuex);const state = { count: 1}export default new Vuex.Store({ state,})

2,通过mapState辅助函数得到全局属性

这种方式的好处是直接通过属性名就可以使用得到属性值了。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选