vuex学习笔记
表示网速太差,本想上传到github,无奈,实在上传不上去。
vuex是一个专门为vue.js设计的集中式状态管理架构。状态?我把它理解为在data中的属性需要共享给其他vue组件使用的部分,就叫做状态。简单的说就是data中需要共用的属性。
安装:npm install vuex --save 一定要加save 安装到生产环境中
卸载 :npm rm vuex
新建一个js文件,放我们的状态,一定要引入vuex和vue,并且使用vuex,代码里面有注释
import Vuex from "vuex"; import Vue from "vue"; Vue.use(Vuex); const store=new Vuex.Store({ //状态值 state:{ count:1 }, //改变状态的方法 mutations:{ /** *add 方法名 * state 状态值 * n 参数 */ add(state,n){ state.count+=n; }, reduce(state){ state.count--; } }, //过滤操作 getters:{ // count:function(state){ // return state.count+=0; // } }, //异步改变状态的方法 actions:{ addActions(aa){ setTimeout(() => { aa.commit('add',2) }, 3000); }, reduceAction(bb){ // console.log(commit); bb.commit('reduce') } } }) export default store;
在新建一个组件,去使用该状态
<template> <div> <h2>{{msg}}</h2> <hr /> <h3>{{count}}</h3> <p> <!--<button @click="$store.commit('add',10)">加</button>--> <button @click="add(1)">加</button> <button @click="$store.commit('reduce')">减</button> </p> <hr/> <p> <!--<button @click="$store.commit('add',10)">加</button>--> <button @click="addActions">actions加</button> <button @click="reduceAction">actions减</button> </p> </div> </template> <script> import store from '@/vuex/store'; import {mapState,mapMutations,mapGetters,mapActions} from 'vuex'; export default { name:"storeCom", data(){return { msg:"hello vuex" }}, //利用计算属性computed来获取count值 // computed:{ // count(){ // return this.$store.state.count;//需要加this // } // }, //通过mapState的对象来赋值 // computed:mapState({ // count:function(state){return state.count} // }), //获取仓库状态,通过mapstate的数组赋值,最简单的写法,推荐 computed: {...mapState(['count']), // count(){return this.$store.getters.count} // ...mapGetters(['count']) }, //获取仓库方法,mapMutations的数组赋值,最简单的写法,推荐 methods:{ ...mapMutations(['add','reduce']), ...mapActions(['addActions','reduceAction']) }, //调用仓库 //getters store } </script> <style> </style>
记得配置路由,ok,完成了
本文来自博客园,作者:zhupan,转载请注明原文链接:https://www.cnblogs.com/zhupanpan/p/10282654.html
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术