Vuex-devtools插件的作用及用法

Vuex-devtools插件用于记录Vue应用中Vuex store的state变化,便于追踪组件对state的修改。在main.js中挂载store到Vue实例,组件通过`this.$store.commit`调用mutations。在组件App.vue中,点击按钮通过mutations成功修改counter,devtools能实时显示并支持调试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

detools插件作用:跟踪记录每一次改变state的状态,从而知道是哪个组件修改了state (前提:state是通过mutations修改)

如下例,目标为通过点击按钮修改mutations中的counter

vuex配置文件index.js

创建store文件夹,在其中创建index.js文件来存放Vuex配置代码

import Vue from 'vue'
import Vuex from 'vuex'

//1、安装插件
Vue.use(Vuex)

//2、创建对象
const store = new Vuex.Store({
      state:{
        counter:0
      },   //state中存放数据
  mutations:{
      increament(state){
        state.counter++
      }    //mutations中确定方法
  }
})

//导出store
export default store

挂载到Vue实例中

为了让所有的Vue组件都可以使用这个store对象:
在main.js中导入store对象,并且放在new Vue中,这样,在其他Vue组件中,就可以通过this.$store的方式,获取到这个store对象

main.js文件:
import Vue from 'vue'
import App from './App'
import store from './store'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  store,
  render: h => h(App)
})

在其他组件中使用store对象

组件App.vue:
<template>
  <div id="app">
    <h2>{{message}}</h2>
    <h2>{{$store.state.counter}}</h2>
    <button @click="addition">按钮</button>
    <hello-vuex :counter="$store.state.counter"></hello-vuex>
  </div>
</template>

<script>
  import HelloVuex from './components/HelloVuex'
  export default {
    name: 'App',
    components: {
      HelloVuex
    },
    data(){
      return {
        message:'你好啊',
      }
    },
    methods:{
      addition(){
        this.$store.commit('increament') //提交
      }
    }
  }
</script>

<style>

</style>

注:在其他组件中使用store对象时,不能直接引用mutations中的方法,需在当前组件的methods中,通过this.$store.commit(‘store对象中方法’) 的方式


效果:


点击按钮后,成功通过mutations修改counter,并且能够在devtools进行实时跟踪,需要时,还能对每一步进行调试

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值