0
点赞
收藏
分享

微信扫一扫

Vuex的简介以及入门案例

北邮郭大宝 2023-10-14 阅读 55
flutterios

Vuex介绍

Vuex是一种状态管理模式,它专为Vue.js应用程序开发设计。使用Vuex能够更好地组织Vue.js应用中的代码,并使代码更容易理解和维护。

Vuex的核心概念包括state、getter、mutation、action、module等。

总之,Vuex是Vue.js应用中一种非常实用的状态管理工具,让我们可以更好地管理和维护应用的状态数据。

图像解析

官方图像解析

传值的图像解析  

Vuex的入门案例

下载我们的Vuex的插件   npm install vuex -S​​​​​​​

Vuex的存值和取值

搭建Vue界面 
page1
<template>
  <div style="padding: 70px;">
    <h1>第一个界面</h1>
    <p>改变值</p>
    请输入<input v-model="msg">
    <button @click="fun1">获取值</button>
    <button @click="fun2">改变值</button>
    <button @click="fun3">改变值(异步请求)</button>
    <button @click="fun4">改变值(异步请求后台数据)</button>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        msg: '默认值'
      }
    },
    methods: {
      fun1() {
        let eduNames = this.$store.state.eduName;
        alert(eduNames);
      },
      fun2() {
        this.$store.commit('setEeduName', {
          eduName: this.msg
        })
      },
      //异步请求
      fun3() {
        this.$store.dispatch('setEeduNameAsync', {
          eduName: this.msg
        })
      },
      fun4(){
       this.$store.dispatch('setEeduNameAjax', {
         eduName: this.msg,
         _this:this
       })
      }
    }
  }
</script>

<style>
</style>
page2
<template>
  <div>
    <h1>第二个界面</h1>
    {{eduName}}
  </div>
</template>
<script>
  export default {
    data() {
      return {
        msg: '默认值'
      }
    },
    computed: {
      eduName() {
        return this.$store.getters.getEeduName;
      }
    }
  }
</script>

<style>
</style>
搭建架子
import page1 from '@/views/vuex/page1'
import page2 from '@/views/vuex/page2'
 
 
 {
          path: '/vuex/page1',
          name: 'page1',
          component: page1
        },
        {
          path: '/vuex/page2',
          name: 'page2',
          component: page2
        }
定义变量

在我们的state.js中定义变量

//  定义变量
export  default {
    eduName:'5211314'
}
mutations.js
//设置值
export  default {
    setEeduName:(state,payload)=>{
     
       state.eduName=payload.eduName;
    }
}
getter.js
// /取值
export  default {
    getEeduName:(state)=>{
     return state.eduName;
    }
}
整合资源
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import getters from './getters'
import actions from './actions'
import mutations from './mutations'
Vue.use(Vuex)

const store = new Vuex.Store({
 	state,
 	getters,
 	actions,
 	mutations
 })
 export default store

举报

相关推荐

0 条评论