9.Vuex

一、前言

SPA模式下,如果数据和方法只能在当前组件访问和使用,其他组件是无法读取和修改的,那么这样明显是不合理的。这里我们就引入了一个vuex的概念。vuex就是设计用来统一管理组件状态的,它定义了一系列规范来使用和操作数据,使组件的应用更加高效。

二、Vuex

1.用法

在使用vuex插件之前先安装,使用命令:cnpm install vuex --save,它的使用和Vue Router相似,也需要先导入,然后调用Vue.use()使用。
我们先通过一个计数器的案例来引入Vuex的使用,具体步骤如下,在src文件夹下新建store文件夹,里面存放整个项目需要的共享数据,在store下新建index.js

//store/index.js
import Vue from  'vue'
import Vuex  from 'Vuex'
Vue.use(Vuex);
export default new Vuex.Store({
    // state存放所有共享数据
   state :{
      count : 0,
   },
   mutations:{
     increment:state =>state.count++,
     decrement:state =>state.count--
   }
   
});
// helloWorld.vue
<template>
  <div class="hello" >
    <h1>监听count的改变{{count}}</h1>
     <Button type="info" @click="increment">+</Button>
    <Button type="info" @click="decrement">-</Button>
  </div>
</template>

<script>

export default {
  
  computed:{
    count(){

      return this.$store.state.count;
    }

  },
  methods:{
     increment(){
      this.$store.commit("increment");
          
     },
     decrement(){
      this.$store.commit("decrement");

     }


  }


}
</script>
 
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.parent{
 background-color: pink;
width: 200px;
height: 200px;

}
.child{
background-color: green;
width: 100px;
height: 100px;
margin: 0 auto;


}

</style>
// nain.js
import Vue from 'vue'
import App from './App'
import router from './router'
import iView from 'iview'
import store from '@/store'
import 'iview/dist/styles/iview.css'
import VueRouter from 'vue-router'
Vue.config.productionTip = false
Vue.use(VueRouter);
Vue.use(iView);
/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})

运行结果,

image.png

当我们点击+的时候,count会增加,点击-的时候,count会减少。如图,
image.png

    1. 使用this.$store.state.count来获取count的值
  • 2.使用commit来调用Vuexmutations里面的方法
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、什么是Vuex Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有...
    紫月凌枫阅读 10,204评论 0 16
  • vuex官方文档 一、vuex是什么 官方解释是:Vuex是通过全局注入store对象,来实现组件间的状态共享,是...
    好一只帅卤蛋阅读 334评论 0 1
  • vuex理解。 Vuex是一个专为Vue.js应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件状态,...
    GXW_Lyon阅读 286评论 0 0
  • 姓名:岳沁 学号:17101223458 转载自:http://blog.csdn.net/h5_queensty...
    丘之心阅读 2,174评论 0 1
  • Vuex是做什么的? 官方解释:Vuex是一个专为Vue.js应用程序开发的状态管理模式。 它采用集中式存储管理应...
    Flipped_kk阅读 379评论 0 4