Vue2.0 中vuex 的简单使用

  • 首先安装vuex插件到项目中
cnpm install vuex --save
  • 在项目的src目录下面建一个store的文件夹,并建一个index.js的文件
//引入vuex
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);
  • 在index.js申明一个状态值count,并声明两个方法来改变该状态值(vuex的状态值只能通过mutations来改变)
const state = {
     count: 1
}
//声明方法来改变count的值
const mutations = {
  add (state,n) {
  if (n) {
  state.count+=n
  } else {
    state.count++
}
  },
  reduce (state) {
    state.count--
  }
}
export default new Vuex.Store({
  state,mutations,getters,actions
})
  • 在main.js中导入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',
  router,
  store,
  components: { App },
  template: '<App/>'
})

在页面的使用vuex中的状态值

<template>
  <div class="hello">
    <h1>{{msg}}</h1>
    <h2>1.直接调用mutation</h2>
    <h3>{{$store.state.count}}</h3>
    <button @click="$store.commit('add')">+</button>
    <!-- 或者直接用-->
    <button @click="$store.commit('reduce')">-</button>
        <button @click="add">+</button>
    <button @click="reduce">-</button>
  </div>
</template>

<script>
  import store from '../store'
  import {mapState, mapMutations, mapGetters, mapActions} from 'vuex'
  export default {
    name: 'HelloWorld',
    data () {
      return {
        msg: 'Hello Vuex'
      }
    },
    methods: {
      ...mapMutations([
        'add','reduce'
      ])
    },
    store
  }
</script>
  • 下面来使用vue的action来改变状态值

在index.js 下面声明action

const actions = {
  addAction(context) {
    context.commit('add',10)
  },
  reduceAction({commit}) {
    commit('reduce')
  }
}

在页面的使用

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <h2>使用action来改变状态值</h2>
    <span>{{ $store.state.count }}</span>
    <button @click="addAction">+</button><button @click="reduceAction">-</button>
  </div>
</template>

<script>
  import store from '../store'
  import {mapState,mapMutations,mapActions} from 'vuex'
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  methods:{
    ...mapActions(['addAction','reduceAction'])
  },
  store
  }
</script>

猜你喜欢

转载自blog.csdn.net/qq_38082304/article/details/79940001