Vuex的介绍和详细使用

news/2024/7/9 23:38:59 标签: vue
  1. 修改state状态必须通过mutations
  2. mutations只能执行同步代码,类似ajax,定时器之类的代码不能在mutations中执行
  3. 执行异步代码,要通过actions,然后将数据提交给mutations才可以完成
  4. state的状态即共享数据可以在组件中引用
  5. 组件中可以调用action

使用部分

1. 安装vuex

第一步:npm i vuex --save => 安装到运行时依赖 (项目上线之后依然使用的依赖 )

npm i vuex --save  
或
npm i vuex -S

2.引入vuex
vue脚手架的src文件夹下的main.js文件中
src=>main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import Vuex from 'vuex'		//引入
Vue.config.productionTip = false

Vue.use(Vuex) //完成Vuex的全局注册,调用了Vuex里面的一个install方法
//实例化Vuex的store
const store=new Vuex.Store() //实例化Vuex的store 实际上所有的 state actions mutations 存于store
new Vue({
  router,
  render: h => h(App),
    store    //es6 属性名和变量名同名时可以缩写
}).$mount('#app')

vuexstate_41">vuex的state使用

1.存放数据

src=>main.js

...
//实例化Vuex的store
const store=new Vuex.Store({
    //存放数据的位置
    state:{
    	//定义一个数据
        count:1
    },
    mutations:{},//同步修改
    actions:{}  //异步修改
})
...

2.获取数据的三种方式

2.1原始方式获取

<template>
  <div class="home">
    <div>原始方式:{{$store.state.count}}</div>
  </div>
</template>

2.2计算属性获取

<div class="home">
    <div>计算属性:{{count}}</div>
</div>
...
export default {
  computed: {
    count () {
      return this.$store.state.count
    }
  }
}

2.3辅助属性获取

<div class="home">
	<div>辅助属性:{{ count }}</div>
	<div>辅助属性:{{ count1 }}</div>
</div>

import { mapState } from 'vuex'
export default {
  computed: {
    ...mapState(['count', 'count1'])
  }
}

mutations的使用

src=>main.js
定义一个方法

// 实例化Vuex的store
...
const store = new Vuex.Store({
  state: {
    count: 1,
    count1: 2
  },
    //定义一个方法
  mutations: {
    addCount (state) {
      state.count += 1
    }
  },
  actions: {}
})
...

原始方法
compontnts => 子组件文件名

<template>
  <div>
    <button @click="addCount">+1</button>
  </div>
</template>

<script>
export default {
  methods: {
    addCount () {
      this.$store.commit('addCount')
    }
  }
}
</script>

带参数的方式
compontnts => 子组件文件名

methods: {
    addCount () {
      this.$store.commit('addCount', 10)
    }
}

src=>main.js

...
mutations: {
	//payload接收到的参数
    addCount (state,payload) {
      state.count += payload
    }
},
...

辅助函数mapMutations方法
compontnts => 子组件文件名

<template>
  <div>
    <button @click="addCount(1)">+1</button>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
export default {

  methods: {
  					   //方法名	
    ...mapMutations(['addCount'])
   
  }
}

src=>main.js

mutations: {
    addCount (state,payload) {
      state.count += payload
    }
},

actions的使用

src=>main.js

 actions: {
    getAsyncCount(context) {
     //异步调用
      setTimeout(function () {
        context.commit('addCount', 123)
      }, 1000)
    }
  }

原始方法
compontnts => 子组件文件名

<template>
  <div>
    <button @click="addCount(1)">+1</button>
    <button @click="test">异步调用</button>
  </div>
</template>

<script>
import { mapMutations, mapActions } from 'vuex'
export default {

  methods: {
    ...mapMutations(['addCount']),
    ...mapActions(['getAsyncCount']),
    test () {
      this.$store.dispatch('getAsyncCount', 111)
    }
  }
}
</script>

辅助函数mapActions
compontnts => 子组件文件名

<button @click="getAsyncCount(1)">辅助函数 Action调用</button>

<script>
import { mapMutations, mapActions } from 'vuex'
export default {
  methods: {
    ...mapMutations(['addCount']),
    ...mapActions(['getAsyncCount'])
  
  }
}
</script>

src=>main.js

  actions: {
    getAsyncCount (context, params) {  		//params 传参
      setTimeout(function () {
        context.commit('addCount', params)   //params 传参
      }, 1000)
    }
  }

getters 过滤属性的使用

src=>main.js

const store = new Vuex.Store({
  state: {
    count: 2,
    count1: 3,
    list:[1,2,3,4,5,6,7,8,9,10]
  },
  
  ...
    
    getters:{
    //筛选
    filterList(state){
      return  state.list.filter(item=>item>5)
    }
 }

Home.vue

 <div>筛选:{{$store.getters.filterList}}</div>
 
 import ChildA from '@/components/Child-a.vue'
import { mapState,mapGetters } from 'vuex'
export default {
  components: {
    ChildA
  },
  computed: {
    ...mapState(['count', 'count1']),
    ...mapGetters(['filterList'])
  }
}

modules模块

src=>main.js

 modules:{
    user:{
      state:{
        token:12345
      }
    },
    setting:{
      state:{
        name:'Vuex实例'
      }
    }
 }

获取
此时获取子模块的状态,需要通过 $store.state.模块名称.属性名

{{$store.state.user.token}} 
{{$store.state.setting.name}} 

导出使用

 getters:{
    filterList(state){
      return  state.list.filter(item=>item>5)
      
    },
    token:state=>state.user.token,	//用一个总的getters向外暴露子模块的属性
    name:state=>state.setting.name  //用一个总的getters向外暴露子模块的属性
  },

使用界面
接收

import {mapGetters} from 'vuex'
 export default {
     computed:{
         ...mapGetters(['token','name'])
     }
}
 </script>

使用

{{token}}
{{name}}

命名空间

src=>main.js

modules: {
    user: {
      state: {
        token: 12345
      },
      mutations: {
          namespaced:true	//加上此句便不会全局调用
        updateToken(state) {
          state.token = 678910
        }
      }
    },
}

引入

<script>
import {mapGetters, mapMutations} from 'vuex'  //引入
 export default {
     computed:{
         ...mapGetters(['token','name'])
     },
     methods:{
         ...mapMutations(['updateToken']) //引入
     }

}
 </script>

调用封闭空间的action
src=>main.js

 modules: {
    user: {
      namespaced:true,

      state: {
        token: 12345
      },
      mutations: {
        updateToken(state) {
          state.token = 678910
        }
      }
    },

调用的方式

<button @click="test">调用封闭空间的action</button>

 methods: {
    ...mapMutations(['user/updateToken']),
    test() {
      this['user/updateToken']() //调用模块的方法
    }
 }

辅助函数调用

 <button @click="updateToken">辅助函数调用封闭空间</button>	!!!
 
 import { mapGetters, createNamespacedHelpers } from 'vuex' !!!
const {mapMutations}=createNamespacedHelpers('user') !!!
export default {
  computed: {
    ...mapGetters(['token', 'name'])
  },
  methods: {
    ...mapMutations(['updateToken']),  !!!
    test() {
      this['user/updateToken']() //调用模块的方法
    }
  }

}

http://www.niftyadmin.cn/n/874991.html

相关文章

python中qt有哪些控件_Python QT组件库qtwidgets的使用

虽然Qt提供了不少现成的组件&#xff0c;但是在Python中使用PyQt5或PySide2进行图形界面程序开发的过程&#xff0c;还是免不了要根据自己的需求组合一些小部件以形成新的自定义组件。最近州的先生在写一个桌面图形界面的登录密码框的过程中&#xff0c;发现了这样一个小巧的自…

React表单里受控组件和非受控组件

通过受控组件和非受控组件两种方式获取表单的值 受控组件 官方说明 React受控组件链接 1.声明 2.将value绑定到声明的对象中 3.绑定onChange改变触发的函数事件 import React, { Component } from reactexport default class App extends Component {//在state中添加一个状…

深度学习的可行性_聚焦深度学习能力 提升阅读教学品质

聚焦深度学习能力 提升阅读教学品质——记厦门五缘第二实验学校《基于深度学习的小学语文阅读教学策略研究》开题报告会2020年11月19日上午&#xff0c;由邓秀娣老师主持的厦门市第五批基础教育课程改革课题《基于深度学习的小学语文阅读教学策略研究》的开题报告会在我校知行苑…

图片相似度识别_人脸识别开放平台及工具

情报分析师全国警务人员和情报人员都在关注虹软&#xff1a;比较推荐和喜欢的一家&#xff0c;有详细的Demo&#xff0c;文档信息等&#xff0c;更重要的是算法免费&#xff0c;而且作为商业算法&#xff0c;它非常简单容易上手。人脸检测&#xff1a;检测人脸位置、锁定人脸坐…

python代码更快的小技巧_一个让Python代码运行更快的最佳方式是什么

Python因其强大、灵活且易于使用等特性&#xff0c;而赢得了声誉。这些优点使其在各种各样的应用程序、工作流程和领域中得到了广泛应用。但是就语言的设计&#xff0c;也就是它天然的解释能力还有它的运行时的动态性而言&#xff0c;Python总是比C或C 这样的机器本地语言慢一个…

python django入门_python之django入门

一.搭建开发环境pip install virtualenv[rootmaster djiango]# find / -name virtualenv/usr/local/bin/virtualenv[rootmaster h1]# source bin/activate(h1) [rootmaster h1]#(h1) [rootmaster h1]#此时已经进入到虚拟环境&#xff1b;(h1) [rootmaster h1]# deactivate …

存储字段数目不明确时如何存储_如何使用GraphQL-基础教程:核心概念

接上篇 —— 如何使用 GraphQL-基础教程&#xff1a;GraphQL 比 REST 的优点 —— 继续翻译How to GraphQL 系列教程。基础和进阶系列翻译已完成&#xff1a;介绍GraphQL 比 REST 的优点核心概念架构客户端服务端更多概念工具和生态安全常见问题在本章中&#xff0c;将学习 Gra…

python大型项目架构图_Flask Web Development —— 大型应用程序结构(上)

虽然小型web应用程序用单个脚本可以很方便&#xff0c;但这种方法却不能很好地扩展。随着应用变得复杂&#xff0c;在单个大的源文件中处理会变得问题重重。与大多数其他web框架不同&#xff0c;Flask对大型项目没有特定的组织方式&#xff1b;应用程序的结构完全交给开发人员自…