vuex

vuex

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。可以想象为一个“前端数据库”(数据仓库),
让其在各个页面上实现数据的共享包括状态,并且可操作

Vuex分成五个部分:
1.State:单一状态树
2.Getters:状态获取
3.Mutations:触发同步事件
4.Actions:提交mutation,可以包含异步操作
5.Module:将vuex进行分模块

vuex使用步骤

安装
cmd 切换到你项目的路径下 输入下载 npm install vuex -S
下载后会显示的下载的版本号

在这里插入图片描述
创建store模块,分别维护state/actions/mutations/getters
store
index.js
state.js
actions.js
mutations.js
getters.js

vuex的核心概念:store、state、getters、mutations、actions

vex相关代码块

</el-menu-item>
    <el-menu-item index="/Page1">
    	<i class="el-icon-s-home"></i>
    	<span slot="title">Page1</span>
    </el-menu-item>
    <el-menu-item index="/Page2">
    	<i class="el-icon-s-home"></i>
    	<span slot="title">Page2</span>
    </el-menu-item>

page1

<template>
    <div style="margin: 15px;">
      <h1>Page1,ts={{ts}}</h1>
      <h2>{{name}}</h2>
    </div>
</template>

<script>
    export default{
      data:function(){
          return{
            ts:new Date().getTime()
          };
        },
        computed:{
          name:function(){
            //不推荐使用
            return this.$store.state.resturantName;
          }
        }
      }
</script>

<style>
</style>

page2

<template>
    <div style="margin: 15px;">
      <h1>Page2,ts={{ts}}</h1>
      <h2>{{name}}</h2>
      <div>
        <button @click="doMutation">mutations之同步方式赋值</button>
        <button @click="doActionAsync">actions之异步方式静态数据赋值</button>
        <button @click="doActionAsyncAjax">actions之异步方式动态数据赋值</button>
      </div>
    </div>
</template>

<script>
    export default{
      data:function(){
          return{
            ts:new Date().getTime()
          };
        },
        methods:{
          doMutation:function(){
            //错误方式
            //this.$store.mutations.setName();
            //正确方式
            this.$store.commit('setName',{
              name:'aaaa'
            });
          },
          doActionAsync:function(){
            this.$store.dispatch('setNameAsync',{
              name:'bbbbbb'
            });
          },
        doActionAsyncAjax:function(){
          this.$store.dispatch('setNameAsyncAjax',{
              name:'cccccc',
              _this:this
            });
          }
        },
        computed:{
          name:function(){
            //不推荐使用
            //return this.$store.state.resturantName;

            //使用getters方式获取值
            return this.$store.getters.getName;
          }
        }
      }
</script>

<style>
</style>

结果图:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值