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