vue中的VueX详解及使用

目标:

1、了解vuex中的各个js文件的用途

2、利用vuex同步存值

3、利用vuex取值

4、Vuex的异步加载问题及后台调用问题

一、VueX简介

 VueX官网:https://vuex.vuejs.org/zh/guide/

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

理解:管理整个前端项目的变量,可以看作前端数据库

二、vuex的五个属性(核心概念),区别和用途

Vue有五个核心概念,stategettersmutationsactionsmodules

   Vuex分成五个部分:

   1.State:单一状态树

   2.Getters:状态获取

   3.Mutations:触发同步事件

   4.Actions:提交mutation,可以包含异步操作

   5.Module:将vuex进行分模块

三、了解vuex中的各个js文件的用途

变量传值的演变形式

图解Vuex各组件

 官方图解Vuex

1. vue中各个组件之间传值

   1.父子组件

   父组件-->子组件,通过子组件的自定义属性:props

   子组件-->父组件,通过自定义事件:this.$emit('事件名',参数1,参数2,...);

   2.非父子组件或父子组件

   通过数据总数Busthis.$root.$emit('事件名',参数1,参数2,...)

   3.非父子组件或父子组件

   更好的方式是在vue中使用vuex

   方法1: 用组件之间通讯。这样写很麻烦,并且写着写着,估计自己都不知道这是啥了,很容易写晕。

   方法2: 我们定义全局变量。模块a的数据赋值给全局变量x。然后模块b获取x。这样我们就很容易获取到数据

四、vuex初步使用步骤

1.安装

      npm install vuex -S

  

2 .创建store模块,分别维护state/actions/mutations/getters

 3. store/index.js文件中新建vuexstore实例,并注册上面引入的各大模块

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

4. main.js中导入并使用store实例

main.js

import store from './store'


new Vue({
  el: '#app',
  data(){
      return{
          Bus:new Vue({
              
          })
      }
  },
  router,
  store,//main.js中导入store实例
  components: { App },
  template: '<App/>'
})

5. 之后按要求编码,即可使用vuex的相关功能

vuexPage1.vue

<template>
    <div>
        <h3>页面1:欢迎来到{{msg}}</h3>
    </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
     
    }
  },
  computed:{//计算属性
     msg(){
     return "KFC";
     }
  }
}
</script>

<style>
</style>
 

6.配置路由

import vuexPage1 from '@/views/sys/vuexPage1'


 {
                path: '/sys/vuexPage1',
                name: 'vuexPage1',
                component: vuexPage1
            }

7.展示结果

五、vuex取值

1.在state.js编写全局要读取的数据

export default{
      resturantName:'慧慧餐馆'
}

2.在VuexPage1和VuexPage2中填写计算属性

computed:{//计算属性
     msg(){
     //return "KFC";
       return this.$store.state.resturantName;
     }
  }

结果:

vuex第二种取值方法:

1.Getterts.js

export default{
    getResturanName:(state)=>{
        return state.resturantName;
    }

}

2.调用

computed:{//计算属性
     msg(){
     //return "KFC";
       //return this.$store.state.resturantName;
         return this.$store.getters.getResturanName;//推荐使用这种
     }
  }

六、vuex存值

1.处理数据的唯一途径,state的改变或赋值只能在这里Mutation.js

export default{
     // type(事件类型): 其值为setResturantName
     // payload:官方给它还取了一个高大上的名字:载荷,其实就是一个保存要传递参数的容器
    setResturanName:(state,payload)=>{
        state.resturantName=payload.resturantName;
    }
}

2.在VuexPage1中添加一个按钮来控制,并且调用Mutation 

<template>
    <div>
        <h3>页面1:欢迎来到{{msg}}</h3>
        <button @click="nx">拿下</button>
    </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
     
    }
  },
    methods:{
        nx(){
            this.$store.commit("setResturanName",{//载荷
                resturantName:"xxx仓管"
            })
        }
    },

  computed:{//计算属性
     msg(){
     //return "KFC";
       return this.$store.state.resturantName;
     }
  }
}
</script>

<style>
</style>
 

 运行结果:

 七、Vuex异步加载

1.编写store/Action.js

export default{
    setResturanNameAsync:(context,payload)=>{
        //context等价与this.$store,也就是他代表了vuex的上下文
        //state.resturantName=payload.resturantName;
    //在这个文件中是可以调用同步文件mutation.js定义的同步方法
    //context.commit("setResturanName",payload);
    //为了让结果明显
    setTimeout(function(){
        context.commit("setResturanName",payload);//同步里面调异步
    },6000);
    }
}

2.在VuexPage1中调用Action.js中的setResturantNameAsync

<button @click="nxAsync">最后主人</button>


 nxAsync(){
        this.$store.dispatch("setResturanNameAsync",{//载荷
            resturantName:"最后的主人"
        })
        }

3.输出结果

 八、后台交互

1.在store/Mutation.js中编写doAjax方法

 export default{
     // type(事件类型): 其值为setResturantName
     // payload:官方给它还取了一个高大上的名字:载荷,其实就是一个保存要传递参数的容器
    setResturanName:(state,payload)=>{
        state.resturantName=payload.resturantName;
    },
    doAjax:(state,payload)=>{
        //需求:想在当前的文件中与后台服务器做数据交互
        let _this= payload._this;
        let url = _this.axios.urls.SYSTEM_MENU_TREE;
        _this.axios.post(url, {}).then((resp) => {
            console.log(resp);
        }).catch(function(error) {
            console.log(error);
        });
        
        
    }
}

在调用doAjax中_this:this是因为Mutation.js获取不到urls,需要用它来代替

2. 在VuexPage1中调用doAjax

<button @click="doAjax">vuex与后台交互</button>


doAjax(){
        this.$store.commit("doAjax",{
            _this:this
        })
    },

结果:

 

  • 7
    点赞
  • 50
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue.js是一个流行的JavaScript框架,它允许您构建动态Web应用程序。Vuex是一个专为Vue.js应用程序开发的状态管理模式。它允许您在应用程序管理和维护状态,例如用户信息、购物车、主题等。Vuex将状态存储在一个集的存储库,称为store。Vuex的核心概念包括state、mutations、actions和getters。 - state:存储应用程序级别的状态,可以通过store.state访问。 - mutations:用于更改状态的函数,必须是同步函数。可以通过store.commit方法调用。 - actions:用于处理异步操作的函数,可以包含任意异步操作。可以通过store.dispatch方法调用。 - getters:用于从store获取状态的函数,可以通过store.getters访问。 下面是一个简单的示例,演示如何在Vue.js应用程序使用Vuex: 1.安装Vuex ```shell npm install vuex --save ``` 2.创建store ```javascript import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment (state) { state.count++ } }, actions: { incrementAsync ({ commit }) { setTimeout(() => { commit('increment') }, 1000) } }, getters: { getCount: state => { return state.count } } }) export default store ``` 3.在Vue组件使用store ```javascript <template> <div> <p>Count: {{ count }}</p> <button @click="increment">Increment</button> <button @click="incrementAsync">Increment Async</button> </div> </template> <script> import { mapGetters, mapActions } from 'vuex' export default { computed: { ...mapGetters([ 'getCount' ]) }, methods: { ...mapActions([ 'increment', 'incrementAsync' ]) } } </script> ``` 在上面的示例,我们创建了一个名为count的状态,并定义了一个名为increment的mutation和一个名为incrementAsync的action。我们还定义了一个名为getCount的getter,用于从store获取count状态。在Vue组件,我们使用mapGetters和mapActions帮助程序将getter和action映射到组件

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值