每日一个前端小知识之vuex

什么是vuex?

官方的解释是Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 + 库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

人话:就是一个数据库,我们在学习vue过程中数据传递只能在通过prop和自定义函数在父子组件中传递,但是通过状态管理库我们可以在任意两个组件之间进行数据传递

vuex的安装流程

第一步:安装vuex

npm install vuex@next --save

第二步:创建一个sotre的文件夹并且在里面新建一个index.js,编写如下

import {createStore} from "vuex"

export default createStore({
    state:{
        conter:0
    }
})

 第三步:在main.js修改如下

import './assets/main.css'

import { createApp } from 'vue'
import App from './App.vue'
import store from '../store'
createApp(App).use(store).mount('#app')

第四步:在app.vue中引入数据

<template>
 <p>counter={{ $store.state.counter }}</p>
 <p>couner={{ couner }}</p>
</template>
<script>
import {mapState} from 'vuex'
export default {
  computed:{
    ...mapState(["couner"])
  }
}
</script>

这里写了两种引入方式,最后都能在页面显示counter=0

vuex状态管理核心(主要使用方法):state,getter,mutation,action

getter:对vuex中的数据进行过滤

mutation:修改vuex中的数据

action:类似于mutation,但是为了异步操作准备的,mutation只能在同步操作中进行(这里不进行样例展示)

对store的index.js修改如下

import {createStore} from 'vuex'
export default createStore({
    state:{
        counter:0
    },
    getters:{
        getcounter(state){
            return state.counter>0?state.counter:"数据异常"
        }
    },
    mutations:{
        addcounter(state,num){
            state.counter+=num;
        }
    }
})

对app.vue修改如下

<template>
 <p>counter={{ $store.getters.getcounter }}</p>
 <p>counter={{ getcounter }}</p>
 <button @click="addClickHandle"></button>
</template>
<script>
import {mapState,mapGetters,mapMutations} from 'vuex'
export default {
  computed:{
    ...mapState(["couner"]),
    ...mapGetters(["getcounter"])
  },
  methods:{
    ...mapMutations(["addcounter"]),
    addClickHandle(){
      // this.$store.commit("addcounter",15)
      this.addcounter(15)
    }
  }
}
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值