02. vuex 中 state

本文主要探讨在 Vuex 中如何管理和使用状态(State)。通过分析 `main.js` 文件和 `state.vue` 组件,了解 Vuex 如何在 Vue 应用中集中存储和管理全局状态,并学习如何在组件中注入和访问 State。

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

main.js

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

Vue.use(Vuex)

export default new Vuex.Store({
  // data
  state: {
    count: 0,
    msg: 'hello world',
    num: 11,
    val: 12
  },
  // methods 外部用 this.$store.commit调用
  mutations: {
    addNum(state) {
      state.count++
    },
    setNum(state, val) {
      state.num = val
    }
  },
  // 异步方法
  actions: {
    
  },
  // 模块
  modules: {
  },
  // 相当于 computed getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
  getters: {

  }
})

state.vue

<template>
   <div>
     <h1>msg: {{msg}}</h1>
     <h3>num: {{num}}</h3>
     <h3>val: {{val}}</h3>
     <input type="text" v-model="resolve">
     <input type="text" :value="num" @change="changeValue">
   </div>
</template>

<script>
  import { mapState } from 'vuex'
  export default {
    name: "state",
    data() {
      return {
        nums: 'abc'
      }
    },
    // 第一种映射方式  数组方式
    // computed: mapState(['msg', 'num', 'val']),
    // methods: {
    //   changeValue: function (e) {
    //     this.$store.commit('setNum', e.target.value)
    //   }
    // }

    // 第二种映射方式  函数的方式
    // computed: mapState({
    //   msg: 'msg',
    //   num: (state) => state.num,
    //   val: function(state) {
    //     return this.nums + state.val
    //   }
    // })

    // 第三种映射方式  将mapState对象结构,成computed里面的属性
    computed: {
      resolve: function () {
        return this.nums.split('').reverse().join('')
      },
      ...mapState({
        msg: 'msg',
        num: (state) => state.num,
        val: function(state) {
          return this.nums + state.val
        }
      })
    }
  }
</script>

<style scoped>

</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值