前端之Vuex

主要解决租价之间传值的问题。

复制代码
npm install vuex@3/4
复制代码
state:用于存储应用程序的状态数据
mutations:用于修改状态数据,外部不要直接对state进行修改。
getter:对状态数据进行处理例如过滤操作。
action:异步操作,网络请求是异步操作,该步骤在action中进行。
module:做数据隔离,针对不同模块下的应用设置不同数据。

具体的使用方法。

①新建一个js文件,里面专门存放State

html 复制代码
import Vue from "vue";
import Vuex from "vuex"
Vue.use(Vuex)


const store = new Vuex.Store({
    state:{
        count:0,
        todos: [
            { id: 1, text: '吃饭', done: true },
            { id: 2, text: '睡觉', done: false }
          ]
    },
    mutations:{
        increment(state,n){
            state.count+=n
        }
    },
    getters:{
        doneTodos:state=>{
            //对于todos数组中每一个元素todo,如果todo.done为true啧该元素增加到新数组中,作为最终的返回。
            //箭头函数,箭头前是参数,箭头后取出箭头前参数的属性
            return state.todos.filter(todo =>todo.done)
        }
    }

})
export default store

创建好以后这个state就是数据仓库了

②在main.js中引入注入这个store机制

html 复制代码
import Vue from 'vue'
import App from './App.vue'
import store from "./store/index"

Vue.config.productionTip = false

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

③在组件中调用

注意其中的计算属性中使用...mapState,....mapGetters,以及方法中使用...mapMutations...mapActions就是对四种机制的映射,让我们使用起来更加方面,具体的映射可以看官网

html 复制代码
<template>
  <div class="hello">
    {{ count }}
    <button @click="myadd">状态加一</button>
    <ul>
      <li v-for="todo in doneTodos" :key="todo.id">{{ todo.text }}</li>
    </ul>
  </div>
</template>

<script>
import { mapState, mapGetters, mapMutations, mapActions  } from 'vuex';

export default {
  name: 'HelloWorld',
  computed:{
    ...mapState([
      'count',
      "todos"
    ]),
    ...mapGetters([
      "doneTodos"
    ]),
    
  },
  methods:{
    ...mapMutations([
      "increment"
    ]),
    ...mapActions([
      "increment"
    ]),
    myadd(){
      // this.$store.commit("increment",3)
      this.increment(3)
    }
  },
  props: {
    msg: String
  },
  
}
</script>

④module

module是面向不同模块的数据隔离。

复制代码
const moduleA = {
  state: () => ({ ... }),
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const moduleB = {
  state: () => ({ ... }),
  mutations: { ... },
  actions: { ... }
}

const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
})

store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态
相关推荐
weixin_427771612 小时前
前端调试隐藏元素
前端
爱上好庆祝3 小时前
学习js的第五天
前端·css·学习·html·css3·js
C澒4 小时前
IntelliPro 产研协作平台:基于 AI Agent 的低代码智能化配置方案设计与实现
前端·低代码·ai编程
一袋米扛几楼984 小时前
【Git】规范化协作:详解 GitHub 工作流中的 Issue、Branch 与 Pull Request 最佳实践
前端·git·github·issue
网络点点滴4 小时前
前端与后端的区别与联系
前端
EnCi Zheng4 小时前
M5-markconv自定义CSS样式指南 [特殊字符]
前端·css·python
kyriewen4 小时前
你的网页慢,用户不说直接走——前端性能监控教你“读心术”
前端·性能优化·监控
广州华水科技4 小时前
北斗GNSS变形监测在大坝安全监测中的应用与优势分析
前端
前端老石人5 小时前
前端开发中的 URL 完全指南
开发语言·前端·javascript·css·html
CAE虚拟与现实5 小时前
五一假期闲来无事,来个前段、后端的说明吧
前端·后端·vtk·three.js·前后端