VueX的简单上手

每一个 Vuex 应用的核心就是 store(仓库)。“store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。Vuex 和单纯的全局对象有以下两点不同:
1.Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。
2.你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。这样使得我们可以方便地跟踪每一个状态的变化

简单理解就是 vueX管理着一个web应用的全局变量

用法

1.可以在src目录下创建一个文件夹并命名为store
在store文件夹下创建 store.js文件

2.在main.js配置如下
主要新增了两条:
1)import store from ‘@/store/store.js’
2)注释//使用store那句

import Vue from 'vue'
import App from './App'
import router from './router'
import store from '@/store/store.js'

Vue.config.productionTip = false

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

3.在需要使用的vue组件中。当然也可以全局引入。

import store from '@/store/store.js'

以下是demo源码,仅供参考

store.js:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

let getters = {
    countPlusTen(state,getters,rootState){
        return state.count+10;
    }
}

let  mutations = {
    increment: state => state.count++,
    decrement(state){
    return state.count=state.count-1;
  },
  //更改 Vuex 的 store 中的状态的唯一方法是提交 mutation
  //上面是 => 和 对等的普通写法
}

let actions = {
  increment (state) {
    state.commit('increment');
  },
  decrement (state) {
    state.commit('decrement');
  },
  //主要是操作mutations
}

export default new Vuex.Store({
  state: {
    count:1,
  },
  getters,
  mutations,//操作方法
  actions,//一般把参数传递给mutations操作
})

2.main.js (上面有,就不再贴了)

3.vue组件

<template>
  <div class="container">
    <h1 style="color:#000;font-size:3rem;" >
      {{$store.state.count}}
    </h1>
    <h1 style="color:#000;font-size:3rem;" >
      {{this.countPlusTen()}}
    </h1>
    <button @click="increment">+</button>
    <button @click="decrement">-</button>
  </div>
</template>

<script>
import store from '@/store/store.js'
export default {
  name: 'HelloWorld',
  data () {
    return {
      count: 0,
    }
  },
  computed:{
    count(){
      return store.state.count;
    }
  },
  methods: {
    increment () {
      store.dispatch('increment');//dispatch调用actions
      //actions 用conmmit 调用mutations
    },
    decrement () {
      store.dispatch('decrement');
    },
    countPlusTen(){
      return store.getters.countPlusTen;
    },
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>

猜你喜欢

转载自blog.csdn.net/m0_37130263/article/details/81080837