vuex的使用

vuex的作用:存储公共变量。

1.首先安装:npm install vuex --save

2.挂在在vue对象上

在main文件中引入使用

import store from './store/index.js'

import Vuex from 'vuex'

Vue.use(Vuex)

 

 

3.在src下面新建文件 index.js入口

 

 index.js内容:

复制代码
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
     msg:'测试'
  },
  mutations: {
     SET_MSG: (state, msg) => {
      state.msg = msg
    },
  },
  actions: {

  },
  getters
})
复制代码

访问说明:

state相当于 组件中的data 里面存储变量

mutations:相当于methods 是一些数据的处理方法

getters:相当于过滤器

在组件中使用state的方法同router相似

使用:this.$store.state.变量名  就可以获取 与赋值

在插值表达式中{{ $store.state.变量名 }}

 

三个常用辅助函数 mapstate  mapActions  mapMutations

 如果想获取上面state里面的msg值,一般做法是 this.$store.state.msg 这样写起来比较麻烦,用辅助函数的话就变成:

 

复制代码
<template>
  <div>
    
  </div>
</template>
<script type="text/javascript">
  import { mapState } from 'vuex';
  export default {
    data() {
      return {
        
      }
    },
    methods: {
      
    },
    computed: {
        ...mapState({
          msg: msg => state.msg
        })
    },
    mounted() {
      console.log(this.msg); 
    }
  }
</script>
复制代码

同样 如果不使用 mapMutations的话,调用mutations里面的方法时这样:this.$store.commit('SET_MSG', '哈哈')。使用了mapMutation后变成:

复制代码
<template>
  <div>
  </div>
</template>
<script type="text/javascript">
  import { mapMutations } from 'vuex';
  export default {
    data() {
      return {
        
      }
    },
    created() {
      this.SET_MSG('123');
    },
    methods: {
      ...mapMutations({
        'SET_MSG': 'SET_MSG'
      }),
  }
</script>
复制代码

 

posted @   .NET_海  阅读(126)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
点击右上角即可分享
微信分享提示