美文网首页
vuex学习笔记(mapState,mapMutations)

vuex学习笔记(mapState,mapMutations)

作者: 不忘初心_d | 来源:发表于2019-10-08 11:04 被阅读0次

欢迎加我技术交流QQ群 :811956471

感谢csdn一位博主的博客,让我对vuex有了更深的了解,原文地址(共三篇):https://blog.csdn.net/gavincz/article/details/81046281

一、安装:npm install vuex --save;

二、引入:在src文件下新建文件夹store,在里面建index.js(名字随便起,个人习惯);

index.js文件写入代码:

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
  state: {
    count: 0 //定义了一个公共属性,并初始化赋值为 0 
  },
  mutations: {
    add(state,n) { 
      state.count+=n
    },
    reduce(state,n) { 
      state.count-=n
    }
  },
  actions: { },
})

三、在入口文件main.js中引入:代码如下:

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from '@/store' //此处全局引入
Vue.config.productionTip = false
new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

四、最好在任意页面中引用state里面的数据、调用mutations里面的方法去更新state里面数据

<template>
  <div class="home">
    <!-- <button class="btn" @click="$store.commit('add',1)">点击加</button>
    <button class="btn"  @click="$store.commit('reduce',2)">点击减</button> -->
    <button class="btn" @click="add(2)">点击加</button>
    <button class="btn" @click="reduce(1)">点击减</button>
    <div>stor里面的count:{{count}}</div>
  </div>
</template>

<script>
  import {mapState,mapMutations} from 'vuex'
  export default {
    name: 'home',
    data() {
      return {}
     },
    created() {},
    computed: {
      // 方法一:--------------------------------------
      // count(){
      //   return this.$store.state.count
      // },

      //方法二:mapState-------------------------------
      //写法1:(mapState中用对象的形式获取)
      // ...mapState({
      //   count:state=>state.count
      // })
      // 写法2:mapState中用数组的形式获取):
      ...mapState(["count"])
    },
    methods: {
      //方法三:mapMutations -------------------------- 此方法只能写在 methods里面,在其他地方调用即可
      ...mapMutations(['add', 'reduce'])
    }
  }
</script>
<style scoped="scoped">
  .btn {
    display: block;
    width: 90%;
    height: 45px;
    margin: 0 auto;
    margin-bottom: 30px;
  }
</style>

相关文章

网友评论

      本文标题:vuex学习笔记(mapState,mapMutations)

      本文链接:https://www.haomeiwen.com/subject/rresyctx.html