vuex

如果你之前使用过vue.js,你一定知道在vue中各个组件之间传值的痛苦,在vue中我们可以使用vuex来保存我们需要管理的状态值,值一旦被修改,所有引用该值的地方就会自动更新,那么接下来我们就来学习一下vuex是如何修改状态值的:

项目创建后,然后安装vuex,使用命令:npm install vuex --save(安装vuex保存到本地),安装成功后你会看到这个界面:

看到这个界面说明项目启动成功,然后我们在项目的src目录下新建一个目录store,在该目录下新建一个index.js文件,我们用来创建vuex实例,然后在该文件中引入vue和vuex,创建Vuex.Store实例保存到变量store中,最后使用export default导出store:

import Vue from 'vue'
import Vuex from 'vuex'
// 使用vuex
Vue.use(Vuex);

// 创建vuex实例
const store = new Vuex.Store({
 
});

//导出store
export default store;

 

然后我们在main.js文件中引入该文件,在文件里面添加 import store from ‘./store’;,再在vue实例全局引入store对象;

import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
  el: '#app',
  store,
  router,
  components: { App },
  template: '<App/>'
})
 
然后我们就可以开始编写我们的vuex业务代码了,那么,我们的数据如何保存?
vuex中的数据源,我们需要保存的数据就保存在这里,可以在页面通过 this.$store.state来获取我们定义的数据;
 
store的index.js:
// 创建vuex实例
const store = new Vuex.Store(
  {
    state:{
      count:1
      },
    getters:{ //实例类似于计算属性
      getStateCount(state){
        return state.count + 1;
      }
    },
    mutations:{
      add(state){
        state.count = state.count + 1;
      },
      reduction(state){
        state.count = state.count - 1;
      },
    },
    actions:{ //类似vue里面的methods
      addFun(context){
        context.commit('add');
      },
      reductionFun(context){
        context.commit('reduction');
      },
    }
  }
);

//导出store
export default store;

 

vue文件:

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <h2>Essential Links</h2>
    <h3>我是直接从页面上获取的{{this.$store.state.count}}</h3>
    <h3>我是从计算属性获取的{{this.$store.getters.getStateCount}}</h3>

    <button @click="addFun">+</button>
    <button @click="reductionFun">-</button>

  </div>
</template>

<script>
  export default {
    name: 'HelloWorld',
    data () {
      return {
        msg: 'Welcome to Your Vue.js App',
      }
    },
 
    methods:{
 
      addFun(){
        this.$store.dispatch('addFun');
        // this.$store.commit('add');
        },
        reductionFun(){
          this.$store.dispatch('reductionFun');
        // this.$store.commit('reduction');
      }
    }
  }
</script>

原文:https://baijiahao.baidu.com/s?id=1618794879569468435&wfr=spider&for=pc

posted @ 2019-07-11 23:38  花月容一箭穿心  阅读(150)  评论(0编辑  收藏  举报