Vuex入门小例子

1.安装 vuex

npm install vuex –save

2.vuex理解

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

我的理解:可以理解为是一个 全局变量

例如: 模块a / 模块b。

我想 模块b获取模块a的数据。

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

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

我们把模块a 的数据叫 state。全局变量叫store。模块b 叫data

Getter 是一个纯函数,用于接收state 参数。返回你需要取的值

mutation 是对 state 进行修改

action 处理数据,对处理的数据 返回给 mutation 从而对 state 进行修改。

这里写图片描述

什么时候用vuex 呢?

当你连自己写的代码都看不懂的时候。搞不懂组件之间是怎么传值。这个时候就需要用vuex

这里写图片描述

store.js代码部分:

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const state = {
  count: 0,
  name: 'zhangsan',
  hight: '121cm'
}
export default new Vuex.Store({
  state,
  mutations: {
    increment: () => {
      return state.count = state.count + 2;
    },
    decrement: () => {
      return state.count = state.count - 2;
    },
    getMsg: () => {
      state.name = 'lisi';
      state.hight = '180cm';
      return state;
    }
  }
});

main.js代码部分

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import Vuex from 'vuex'
import store from './vuex/store'
Vue.use(Vuex)
Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  store,
  router,
  components: { App },
  template: '<App/>'
})

html代码部分:

<template>
  <div id="app">
    <header>Header</header>
    <router-view/>
    <h1>{{'原始值为:' + count}}</h1>
    <h2>{{'msg:' + msg}}</h2>
    <button @click="add">自增按钮</button>
    <button @click="del">自减按钮</button>
    <button @click="getMsg">获取信息</button>
    <footer>Footer</footer>
  </div>
</template>

<script>
import filters from './Tools/filter.js'
export default {
  name: 'App',
  data () {
    return {
      arr: [1,2,3]
    }
  },
  created() {
    console.log(this.$store);
    console.log(this);
  },
  methods: {
    add () {
      this.$store.commit('increment');
    },
    del () {
      this.$store.commit('decrement')
    },
    getMsg () {
      this.$store.commit('getMsg');
    }
  },
  computed: {
    count () {
      return this.$store.state.count;
    },
    msg () {
      return JSON.stringify(this.$store.state);
    }
  }
}
</script>

<style>
  *{margin:0;padding:0;font-family:"微软雅黑";}
  li{list-style:none;}
  body{padding:100px 0;}
  header,footer{
    position:fixed;
    height:100px;
    width:100%;
    background:blue;
    font-size:30px;
    color:#fff;
    line-height:100px;
    text-align:center;
  }
  footer{bottom:0;}
  header{top:0;}

</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值