首页 > 其他分享 >Vue — VueX

Vue — VueX

时间:2024-03-13 17:13:45浏览次数:19  
标签:count ... Vue VueX state import vuex store

一、VueX概述

1.概述:

vuex是一个vue的状态管理工具,状态就是数据;可以帮助我们管理vue通用的数据(多组件共享的数据)

2.场景:

(1)某个状态在很多个组件中使用 例如 个人信息 

(2)多个组件共同维护一份数据 例如 购物车

3.优势:

(1)共同维护一份数据,数据集中化管理

(2)响应式变化

(3)操作简单(vuex提供了函数方法)

二、构建VueX【多组件数据共享】

1.创建项目 vue create  app

2.创建一个空仓库

(1)安装vuex   vue2.0安装vuex@3   vue3.0安装vuex@4

npm i vuex@3

(2)新建vuex模块文件

(3)创建仓库

//引入核心包
import Vuex from 'vuex'
import Vue from 'vue'

//插件注册
Vue.use(Vuex)

//创建仓库
 const store = new Vuex.Store()
export default store

(4)main.js导入挂载

import Vue from 'vue'
import App from './App.vue'
import store from './store'

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
  store
}).$mount('#app')

三、使用store仓库

1.state状态

(1)提供数据:

State提供唯一的公共数据源,所有共享的数据都要统一放到Store中的State存储。在state对象中可以添加我们要共享的数据。

(2)使用数据:

-通过store直接访问(模板中、组件逻辑中、js中)

-通过辅助函数简化

<template>
  <div class="box">
    <div class="boxA">
      A组件
      <p>{{ title }}
        {{ count }}</p>
    </div>

  </div>
</template>

<script>

import {mapState} from 'vuex'

export default {

  computed:{
    ...mapState(['title','count'])
  }
}
</script>

(3)修改数据 (mutations)

vuex同样遵循单项数据流,组件中不能直接修改仓库的值

2.mutations

(1)定义mutations对象,对象中存放修改state的方法

const store = new Vuex.Store({
    strict : true,
    state : {
        title : '共享标题',
        count : 100
    },
    mutations : {
        //第一个参数是state
        addCount(state){
            state.count+=1
        }
    }
})

(2)组件中提交调用mutation

<button @click="add">count+1</button>

add(){
      this.$store.commit("addCount") }

(3)传参 只能额外传递一个参数

 mutations : {
        //第一个参数是state
        addCount(state,n){
            state.count+=n
        }
    }
<button @click="add(1)">count+1</button>
<button @click="add(5)">count+5</button>
<button @click="add(10)">count+10</button>
<button @click="add(20)">count+20</button>

this.$store.commit("addCount",n)

(3)mapMutations(映射store的方法)

import {mapState,mapMutations} from 'vuex'

export default {

  computed:{
    ...mapState(['title','count'])
  },
  methods :{
    ...mapMutations(['addCount','reduceCount'])
  }
}
<button @click="addCount(20)">count+20</button>
<button @click="reduceCount(20)">count-20</button>

3.actions (处理异步操作)

mutationa是同步的

(1)提供action方法

const store = new Vuex.Store({
    strict : true,
    state : {
        title : '共享标题',
        count : 100,
        number : 66
    },
    mutations : {
        //第一个参数是state
        addCount(state,n){
            state.count+=n
        },
        reduceCount(state,n){
            state.count-=n
        },
        changeNum(state,num){
            state.number = num
        },

    },
    actions : { //处理异步,不能直接操作state
        //context:上下文 没有分模块,可以当做store仓库
        //context.commit('mutations名字',参数)
        changeCountAsync(context,num){
            setTimeout(()=>{
                context.commit('changeNum',num)

            },2000)
        }
    }
})

(2)页面中dispath调用

<button @click="changeAsync">异步</button>
 methods :{
    changeAsync(){
      this.$store.dispatch('changeCountAsync','8')
    }
  }

(3)mapActions(映射actions的方法,映射到组件的methods)

  <button @click="changeCountAsync(9999999)">异步</button>

<script>

import { mapState, mapMutations, mapActions } from 'vuex'

export default {

  computed: {
    ...mapState(['title', 'count'])
  },
  methods: {
    ...mapMutations(['addCount', 'reduceCount']),
    ...mapActions(['changeCountAsync'])
  }
}
</script>

4.getters(类似计算属性)

除了state,我们还需要从state中派生出一些状态,这些状态是依赖state的,此时会用到getters

(1)定义getters

    getters : {
        //形参第一个参数就是state
        //必须有返回值 返回值就是getters的值
        filterList(state){
            return state.list.filter(item=>item>5)
        }
    }

(2)访问getters

<ul>
   <li v-for="(item,index) in $store.getters.filterList" :key="index">{{ item }}</li>
</ul>

(3)mapGetters

import { mapState, mapMutations, mapActions ,mapGetters} from 'vuex'
 computed: {
    ...mapState(['title', 'count','list']),
    ...mapGetters(['filterList'])
  },

<li v-for="(item,index) in filterList" :key="index">{{ item }}</li>

 

标签:count,...,Vue,VueX,state,import,vuex,store
From: https://www.cnblogs.com/qinlinkun/p/18071056

相关文章

  • vue3 生命周期06
    众所周知,vue2有生命周期,而vue3也有而vue2的created和beforecreated在vue3中都由setup替代了<scriptsetuplang="ts">import{onBeforeMount,onMounted,onBeforeUpdate,onUpdated,onBeforeUnmount,onUnmounted}from'vue'console.log('创建生命周期')o......
  • Vue学习笔记50--组件自定义事件
    props--将子组件的信息传递给父组件 <!--通过父组件给子组件传递函数类型的props实现:子给父传递数据-->  <School:getShcoolName="getShcoolName"></School>示例一:App.vue<template><divclass="app"><!--<imgsrc="./assets......
  • vue3 循环引用的解决办法问题,Cannot access ‘xxxx‘ before initialization
    ReferenceError:Cannotaccess‘xxxx‘beforeinitialization ,原因之前已经初始化过,但页面组件嵌套,需要被重复引用。1、开启异步引用来解决components:{DeviceManage:defineAsyncComponent(()=>import('@/views/operation/mechanism/index.vue'))}2、用ifrme来......
  • 2024年最受欢迎的Vue.js组件库 - ViewDesign全面解析
    引言作为现代Web开发不可或缺的一员,Vue.js以其轻量、高效、渐进式的理念备受开发者青睐。而在Vue.js生态系统中,第三方组件库则扮演着桥梁的角色,为开发者提供可复用的UI组件,从而极大提高了开发效率。在2024年,有许多优秀的Vue组件库脱颖而出,但毫无疑问,ViewDesign因其卓越的......
  • Pinia和Vuex有什么区别?
    API设计:Pinia的API设计更加简洁和直观。它采用了类似于VueCompositionAPI的风格,使用了更加现代化的语法和概念。相比之下,Vuex的API设计较为传统,使用了基于对象和字符串的方式来定义和访问状态。TypeScript支持:Pinia天生支持TypeScript,并提供了更好的类型推断和类型安全......
  • 基于Java+Vue+Mysql的门店管理系统(附配套文档和源码)【毕业设计分享】
          前言:门店管理系统是一个综合性的软件解决方案,旨在帮助门店高效地管理日常运营、提升服务质量、优化资源配置和增强决策能力。以下是您提到的各个管理模块的简要概述:门店管理:门店信息管理:记录门店的基本信息,如门店名称、地址、联系方式、营业时间等。门店布局管......
  • 基于Java+Vue+Mysql的WMS仓库管理系统(附配套文档和源码)【毕业设计分享】
          前言: WMS(WarehouseManagementSystem)仓库管理系统是一个用于优化仓库操作、提高效率和准确性的软件解决方案。以下是针对列出的WMS仓库管理系统的各个部分的简要描述:1.订单管理订单管理是WMS的核心功能之一,涉及处理、跟踪和完成客户订单。这包括:订单录入:......
  • Vue的生命周期
    Vue的生命周期Vue的生命周期指的是vm对象从创建到最终销毁的整个过程,在这个过程中不同的时间节点上调用不同的钩子函数(在不同时刻被自动调用的函数)虚拟DOM在内存中就绪时:去调用一个a函数虚拟DOM转换成真实DOM渲染到页面时:去调用一个b函数Vue的data发生改变时:去调用一个......
  • Vue虚拟DOM
    虚拟DOM什么是虚拟DOM虚拟DOM本质上就是一个普通的Js对象,用于描述视图的界面结构为什么需要虚拟DOM树主要为解决渲染效率问题。在vue中,渲染试图会调用render函数,这种渲染不仅发生在组件创建时,同时发生在试图依赖的数据更新时。如果在渲染时,直接使用真实DOM,由于真实DOM的创......
  • Vue学习笔记--浏览器存储(local Storage + session Storage)
    浏览器存储:意思就是本地缓存信息localStorage示例一:<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width,initial-scale=1.0"><ti......