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辅助函数得到全局属性
这种方式的好处是直接通过属性名就可以使用得到属性值了。
将Component.vue的代码进行改变
<template> <div> <h3>{
{
this.$store.state.count}
}
--{
{
count}
}
</h3> <h4>{
{
index2}
}
</h4> </div></template><script> import {
mapState,mapMutations,mapGetters }
from "vuex";
export default {
name:'count', data:function(){
return {
index:10 }
}
, //通过对象展开运算符vuex里的属性可以与组件局部属性混用。 computed:{
...mapState(['count']), index2() {
return this.index+30;
}
}
, }
</script><style scoped></style>
总结
以上所述是小编给大家介绍的vuex操作state对象的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
您可能感兴趣的文章:
- 简单的三步vuex入门
- vue router+vuex实现首页登录验证判断逻辑
- vuex与组件联合使用的方法
- 详解vuex结合localstorage动态监听storage的变化
- 基于vue,vue-router, vuex及addRoutes进行权限控制问题
- 父组件中vuex方法更新state子组件不能及时更新并渲染的完美解决方法
- vuex进阶知识点巩固