VueX 使用

devtools/2024/10/19 2:18:43/

1.简介

就是用来多组件共享数据的实现用的

  

2.使用VueX

 因为使用的是vue2 所以下的是vuex3 若是vue3 必须下的是 vue4  

npm i vuex@3

3.搭建环境

1.创建 src/store/index.js

javascript">//该文件用于创建一个Vuex中最为核心的store//引入VueX
import Vuex from 'vuex'
import Vue from 'vue'
//准备 actions - 用于响应组件中的动作
const actions = {}//准备 mutations - 用于操作数据(state)
const mutations = {}//准备 state - 用于存储数据
const state = {}Vue.use(Vuex)//创建 store
const store = new Vuex.Store({actions,mutations,state
});//暴露store
export default store;

2.main.js引入

javascript">//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//引入vue-resource
import vueResource from 'vue-resource'//引入store
import store from './store/index'//关闭Vue的生产提示
Vue.config.productionTip = false//应用插件
// import plugins from './plugins'
//使用插件
// Vue.use(plugins,1,3,2,5,6)// const d = Vue.extend({}); // Vue.prototype.eventBus= new d();//使用插件
Vue.use(vueResource)//创建vm
new Vue({el: '#app',render: (h) => h(App),//放入构造出 App组件模板store,beforeCreate() {Vue.prototype.$bus = this; //安装全局事件总线// console.log(this);}
})

3.使用

store 下 建 index.js

javascript">//该文件用于创建一个Vuex中最为核心的store//引入VueX
import Vuex from 'vuex'
import Vue from 'vue'
//准备 actions - 用于响应组件中的动作
const actions = {jia(context,value){console.log('actions中的jia被调用了',context ,value);context.commit('JIA',value);},jian(context,value){console.log('actions中的jian被调用了',context ,value);context.commit('JIAN',value);},jiaOdd(context,value){console.log('actions中的jiaOdd被调用了',context ,value);if(context.state.sum % 2){context.commit('JIA',value);}},jiaWait(context,value){console.log('actions中的jiaWait被调用了',context ,value);setTimeout(() => {context.commit('JIA',value);}, 1000);}
}//准备 mutations - 用于操作数据(state)
const mutations = {JIA(state,value){console.log('mutations中的jia被调用了',state ,value);state.sum+=value;},JIAN(state,value){console.log('mutations中的jian被调用了',state ,value);state.sum-=value;}
}//准备 state - 用于存储数据
const state = {sum:0,
}Vue.use(Vuex)//创建 store
const store = new Vuex.Store({actions,mutations,state
});//暴露store
export default store;

4.在组件中调用

javascript"><template><div><h2>当前求和为:{{ $store.state.sum }}</h2><select v-model.number="n"><option value="1">1</option><option value="2">2</option><option value="3">3</option></select><button @click="increment">+</button><button @click="decrement">-</button><button @click="incrementOdd">当前求和为奇数再加</button><button @click="incrementWait">等一等再加</button></div>
</template><script>
export default {name: "CountComponent",data() {return {n: 1,};},methods: {increment() {this.$store.commit("JIA", this.n);},decrement() {this.$store.commit("JIAN", this.n);},incrementOdd() {this.$store.dispatch("jiaOdd", this.n);},incrementWait() {this.$store.dispatch("jiaWait", this.n);},},
};
</script><style scoped>
button {margin-left: 5px;
}
</style>

4.getters的使用

相当于全局的计算属性

 5.mapActions mapGetter mapState mapMutations

 

6. 多组件共享数据

直接调用里面的数据就行,都是共享的

7.模块化加命名空间

javascript"><template><div><h2>当前求和为:{{ sum }}</h2><h2>当前求和放大10倍为:{{ bigSum }}</h2><h2>我在{{ school }} 学习 {{ subject }}</h2><h2>Persion组件的总人数是:{{personList.length}}</h2><select v-model.number="n"><option value="1">1</option><option value="2">2</option><option value="3">3</option></select><button @click="JIA(n)">+</button><button @click="JIAN(n)">-</button><button @click="jiaOdd(n)">当前求和为奇数再加</button><button @click="jiaWait(n)">等一等再加</button></div>
</template><script>
import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
export default {name: "CountComponent",data() {return {n: 1,};},computed: {...mapState('countAbout',["sum", "school", "subject"]), //同名就可以这样写...mapState('personAbout',['personList']), //同名就可以这样写...mapGetters('countAbout',["bigSum"]),},methods: {...mapMutations('countAbout',["JIA", "JIAN"]),...mapActions('countAbout',["jiaOdd", "jiaWait"]),}};
</script><style scoped>
button {margin-left: 5px;
}
</style>

 

javascript"><template><div><h1>人员列表</h1><h1>Count组件求和为:{{sum}}</h1><h3>列表中第一个人的名字是{{firstPersonName}}</h3><input type="text" placeholder="请输入名字" v-model="name"><button @click="add">添加</button><button @click="addWang">添加一个姓王的人</button><button @click="addOfNet">添加一个网络请求的人</button><ul><li v-for="p in personList" :key="p.id">{{p.name}}</li></ul></div>
</template><script>
import {nanoid} from 'nanoid'
export default {name:'PersonComponent',data() {return {name:''}},computed:{personList(){return this.$store.state.personAbout.personList;},sum(){return this.$store.state.countAbout.sum;},firstPersonName(){return this.$store.getters['personAbout/firstPersonName'];}},methods:{add(){const personObj = {id:nanoid(),name:this.name};console.log(this.$store);this.$store.commit('personAbout/ADD_PERSON',personObj)},addWang(){const personObj = {id:nanoid(),name:this.name};console.log(this.$store);this.$store.dispatch('personAbout/addPersonWang',personObj)},addOfNet(){this.$store.dispatch('personAbout/addPersonServer')}}
}
</script><style></style>
javascript">//该文件用于创建一个Vuex中最为核心的store//引入VueX
import Vuex from 'vuex'
import Vue from 'vue'import countOptions from './count'
import persionOptions from './person'Vue.use(Vuex)//创建 store
const store = new Vuex.Store({modules: {countAbout: countOptions,personAbout: persionOptions}
});//暴露store
export default store;
javascript">//人员管理相关配置
import axios from "axios";
import { nanoid } from "nanoid";
export default {namespaced: true,actions: {addPersonWang(context, value) {if (value.name.indexOf('王') === 0) {context.commit('ADD_PERSON', value);}},addPersonServer(context){axios.get('http://localhost:8080/atjmj/students/atjmj').then(res => {console.log(res.data);context.commit('ADD_PERSON', {id: nanoid(), name: res.data[0].name});}).catch(err => {console.log(err);})}},mutations: {ADD_PERSON(state, value) {console.log('mutations中的ADD_PERSON被调用了', state, value);state.personList.unshift(value);}},state: {personList: [{ id: '001', name: '张三' }]},getters: {firstPersonName(state) {return state.personList[0].name;}}
}
javascript">//求和相关配置
export default {namespaced: true,actions: {jiaOdd(context, value) {console.log('actions中的jiaOdd被调用了', context, value);if (context.state.sum % 2) {context.commit('JIA', value);}},jiaWait(context, value) {console.log('actions中的jiaWait被调用了', context, value);setTimeout(() => {context.commit('JIA', value);}, 1000);}},mutations: {JIA(state, value) {console.log('mutations中的jia被调用了', state, value);state.sum += value;},JIAN(state, value) {console.log('mutations中的jian被调用了', state, value);state.sum -= value;}},state: {sum: 0,school: '尚硅谷',subject: '前端',},getters: {bigSum(state) {return state.sum * 10;}}
}
javascript"><template><div class="appContainer"><CountComponent/><PersonComponent/></div>
</template><script>
import CountComponent from './components/CountComponent.vue';
import PersonComponent from './components/PersonComponent.vue';export default {name: "App",components: {CountComponent,PersonComponent},methods: {},
};
</script><style scoped>
.appContainer {padding: 5px;display: flex;flex-direction: column; /* 垂直方向排列子元素 */justify-content: center;align-items: center;  
}</style>


http://www.ppmy.cn/devtools/97046.html

相关文章

[ABC367C] Enumerate Sequences 题解

[ABC367C] Enumerate Sequences 搜索。 考虑使用 DFS 深搜&#xff0c;对于第 i i i 个数&#xff0c;从 1 1 1 到 r i r_i ri​ 枚举&#xff0c;将 a i a_i ai​ 设为当前枚举的数&#xff0c;并进行下一层递归。 对所有的数填完后&#xff0c;判断当前和是否为 k k …

MyCAT读写分离及实现---MySQL5.7的glibc

中间件代理方式的读写分离&#xff0c;在业务代码中&#xff0c;数据库的操作不直接连接数据库&#xff0c;而是先请求到中间件服务器&#xff08;代理&#xff09;&#xff0c;由代理服务器判断是读操作去从数据服务器&#xff0c;写操作去主数据服务器。 中间件代理服务器&am…

SpringBoot MySQL BinLog 监听数据变化(多库多表)

开始 1&#xff1a;引入mysql-binlog-connector-java.jar <!-- binlog --><dependency><groupId>com.zendesk</groupId><artifactId>mysql-binlog-connector-java</artifactId><version>0.27.1</version></dependency>…

使用DOM破坏启动xss

目录 实验环境&#xff1a; 分析&#xff1a; 找破坏点&#xff1a; 查看源码找函数&#xff1a; 找到了三个方法&#xff0c;loadComments、escapeHTM 、displayComments loadComments escapeHTM displayComments&#xff1a; GOGOGO 实验环境&#xff1a; Lab: Exp…

前端面试——js作用域

说一说JS的作用域吧 作用域的分类 作用域分为&#xff1a;全局作用域&#xff0c;函数作用域&#xff0c;块级作用域 作用域的特性 全局作用域&#xff1a; 能够让变量和函数在全局位置访问&#xff0c;其挂载在浏览器的window对象下面 其中var定义的变量和function函数存…

品牌出海新策略:携手TikTok达人,合作孵化IP实现双赢

在当今数字化时代&#xff0c;TikTok达人的IP孵化作为一种创新的合作模式&#xff0c;正逐渐成为品牌出海的新兴策略。通过与有潜力的TikTok达人合作&#xff0c;共同孵化新的IP&#xff0c;品牌不仅能够突破传统营销的局限&#xff0c;还能实现与达人共同成长的双赢局面。本文…

P1587 [NOI2016] 循环之美

[题目通道]([NOI2016] 循环之美 - 洛谷) #include<map> #include<cmath> #include<cstdio> #include<algorithm> #define fp(i,a,b) for(int ia,Ib;i<I;i) #define file(s) freopen(s".in","r",stdin),freopen(s".out&qu…

Go Channel 详解

概述 在 Go 语言中&#xff0c;channel 是一种用于在 goroutine 之间传递数据的机制。它提供了同步和通信的能力&#xff0c;使得并发编程变得更加简单和安全。Channel 在 Go 语言中的设计是类型安全的&#xff0c;并且支持发送和接收两种操作。 基本概念 创建通道 创建一个…