vuex 使用方法
1、安装vuex扩展 : npm install vuex
2、在componets目录下新建 store.js 文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) // 定义初始值 const state = { num: 0 } // 获取变量值 const getters = { num: state => state.num } //定义触发状态对象方法,传入state整个对象 //在页面中触发时使用this.$store.commit('mutationName') 触发Mutations方法改变state的值 const mutations = { plus(state, num) { state.num += num; }, minus(state, num) { state.num -= num; } } //异步执行方法,传入参数context,等同于整个store //处理Mutations中已经写好的方法 在页面中触发方式是 this.$store.dispatch(actionName) const actions = { plus({commit}, num) { // 调用mutations 方法 commit( 'plus' , num) }, minus({commit}, num) { commit( 'minus' , num) } } export default new Vuex.Store({ state, mutations, actions, getters }) /** * 定义多个模块 * 定义一个模块,引入各个状态对象或方法 */ // Const moduleA = { // state, // mutations, // getters, // actions // } /** * 引如多个模块 */ // export default new Vuex.Store ({ // modules : { // a : moduleA //引入定义模块 // } // }) |
属性值介绍:
state:定义初始值
getters:获取变量值
mutations: 定义触发状态对象方法,传入state整个对象,在页面中触发时使用this.$store.commit('mutationName') 触发Mutations方法改变state的值
actions:异步执行方法,传入参数context,等同于整个store,处理Mutations中已经写好的方法 在页面中触发方式是 this.$store.dispatch(actionName)
3、在main.js 里添加引入store.js 代码
1 2 3 4 5 6 7 8 9 | // 引入sotre.js import store from './components/store.js' new Vue({ store, // store对象 el: '#app', router, render: h => h(App) }); |
4、新建 TestVuex.vue
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | <template> <div class = "testVuex" > <div>{{num}}</div> <button @click= "plus" >加2</button> <button @click= "minus" >加3</button> </div> </template> <script> import {mapGetters} from 'vuex' export default { name: 'testVuex' , //computed 实时计算 Vue检测到数据发生变动时就会执行对相应数据有引用的函数。 computed: { ...mapGetters([ 'num' // store.js 里定义num值 ]) }, methods:{ // 调用store.js 里actions定义的方法 plus: function () { this .$store.dispatch( 'plus' , 2); }, minus: function () { this .$store.dispatch( 'minus' , 3); } }, data () { return { } } } </script> |
5、效果预览
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步