1、概述

Vuex作为插件,管理和维护整个项目的组件状态。

2、安装vuex

cnpm i --save vuex

3、vuex使用

github地址:https://github.com/MengFangui/Vuex

new Vue({
el: '#app',
router: router,
//使用vuex
store: store,
render: h => {
return h(App)
}
});

4、配置项

(1)数据:数据保存在state中。store的数据只能读取,不能改变。

(2)改变store中的数据使用mutations。组件内通过this.$store.commit来执行mutations.

(3)getters提取过滤方法

(4)actions:处理异步操作,组件内通过this.$store.dispatch触发。

涉及数据改变的用mutations,涉及业务逻辑的使用actions。

以上整体配置为:

//vuex的配置
//注意Store是大写
const store = new Vuex.Store({
//数据保存
state: {
count: 0,
list: [1, 5, 8, 10, 30, 50]
},
mutations: {
increase(state, n = 1) {
state.count += n;
},
decrease(state, n = 1) {
state.count -= n;
}
},
getters: {
filteredList: state => {
return state.list.filter(item => item < 10);
}
},
actions:{
asyncIncrease(context){
//异步 1s后执行
return new Promise(resolve=>{
setTimeout(()=>{
context.commit('increase');
//Promise 的一种状态Resolved(已完成)
resolve();
},1000)
})
}
}
});

5、组件代码

<template>
<div>
<h1>首页</h1>
{{count}}
<button @click="handleIncrease">+5</button>
<button @click="handleDecrease">-5</button> <!--getters 用法-->
<div>{{list}}</div>
<!--actions用法-->
<button @click="handleAsyncIncrease">action +1</button> <!--router-link会渲染为一个a标签 实现跳转的方式1-->
<!--router-link 的tag属性 指定渲染成什么标签-->
<!--router-link 的replace属性 不会留下history记录,不能使用后退键-->
<!--router-link 的active-class属性 路由匹配成功时会自动给当前元素设置为一个名为router-link-active的class-->
<router-link to="/about">跳转到 about</router-link>
</div>
</template>
<script>
export default {
computed:{
count(){
return this.$store.state.count;
},
list(){
return this.$store.getters.filteredList;
}
},
methods:{
handleIncrease(){
this.$store.commit('increase',5);
},
handleDecrease(){
this.$store.commit('decrease',5);
},
handleAsyncIncrease(){
this.$store.dispatch('asyncIncrease').then(()=>{
console.log(this.$store.state.count)
});
}
}
}
</script>

vuex 维护多个组件之间的公共(共有)状态!

最新文章

  1. 【JS基础】循环
  2. spring快速入门(三)
  3. 一些pc端web事件移动端不再可行
  4. android 内存问题
  5. 有三个线程T1 T2 T3,如何保证他们按顺序执行-转载
  6. 九度OJ 1544 数字序列区间最小值
  7. android仿win8 metro磁贴布局
  8. 新闻类App使用的组件
  9. IPv6 tutorial – Part 8: Special addresses
  10. eclipse代码格式化
  11. JavaScript中七种函数调用方式及对应 this 的含义
  12. 挺苹果的声音,iPhone 5s的两处进步
  13. LoadRunner编写Socket协议脚本方法
  14. 从性能角度看react组件拆分的重要性
  15. 使用Redis实现分布式锁
  16. python反编译工具
  17. selenium跳过webdriver检测并爬取淘宝我已购买的宝贝数据
  18. 先打11.2.0.3.8这个PSU,后建库
  19. 【转】在.net Core 中像以前那样的使用HttpContext.Current
  20. 编码原则:最小化使用控制结构(条件和循环)续:告别 break 和 continue

热门文章

  1. CentOS7 中把默认yum源更换成163源
  2. 平滑部署war包到tomcat-deploy.sh
  3. (十五)mysql中间件MyCAT实现
  4. 关闭浏览器session就被干掉的假象的问题
  5. bufferknife框架的正确使用方式 -终于他么知道了
  6. NOIP2014飞扬的小鸟
  7. golang笔记:net/smtp
  8. POJ1300Door Man(欧拉回路)
  9. glib wpa_supplicant Unix上库编译错误解决与总结
  10. MathType插入带序号公式的两种方法