Vuex简单使用

第一次使用vuex

(1)创建项目,导入vscode
vue create lean-vuex
(2)关闭eslint(也可以不用,为了第一次便于理解)
创建vue.config.js

module.exports = {
    lintOnSave: false
}

(3)运行项目
npm run serve
(4)查看官方文档
vuex3的文档
(5)安装依赖
npm i vuex@3.6.2
(6)写代码,创建store

import Vue from 'vue'
import App from './App.vue'
import Vue from 'vue'
import App from './App.vue'
//1.导入vuex的模块
import Vuex from 'vuex'
//2.注册vuex,注册组件...
Vue.use(Vuex)
//3.创建store
const store = new Vuex.Store({
  state: {}//定义数据,类似于vue当中data
})

Vue.config.productionTip = false

new Vue({
  //4.挂载store,会在组件this上面添加$xxx
  store,
  render: h => h(App),
}).$mount('#app')

(7)写代码,使用state,mutations,actions

<template>
  <div id="app">
    <!-- 使用state方式1-直接使用 -->
    <div>count: {{$store.state.count}}</div>
    <!-- 使用state方式2-自定义计算属性 -->
    <div>count: {{count}}</div>
    <div>username: {{username}}</div>
    <!-- 调用mutations的方式1-直接调用 -->
    <button @click="$store.commit('add')">+1</button>
    <!-- 调用mutations的方式2-映射调用 -->
    <button @click="add">+1</button>

    <!-- mutations的传参 -->
    <button @click="$store.commit('addN', 3)">+N</button>
    <button @click="addN(3)">+1</button>


    <!-- 调用actions的方式1-直接调用 -->
    <button @click="$store.dispatch('addSync')">+1 async</button>
    <!-- 调用mutations的方式2-映射调用 -->
    <button @click="addSync">+1 async</button>

    <!-- actions的传参 -->
    <button @click="$store.dispatch('addNSync', 3)">+N async</button>
    <button @click="addNSync(3)">+N async</button>

    <!-- 使用getters的方式1-直接调用 -->
    <div>{{$store.getters.showCount}}</div>
    <!-- 使用getters的方式2-映射调用 -->
    <div>{{showCount}}</div>
  </div>
</template>

<script>
import {mapState, mapMutations,mapActions,mapGetters} from 'vuex'
export default {
  name: 'App',
  methods: {
    //通过mapMutations批量生成方法
    ...mapMutations(['add','addN']),
    //通过mapActions批量生成方法
    ...mapActions(['addSync','addNSync'])
  },
  computed: {
    ...mapGetters(['showCount']),
    //通过mapState来批量生成计算属性
    ...mapState(['count', 'username'])
    /*
    count(){
      return this.$store.state.count
    },
    username(){
      return this.$store.state.username
    }
    */
  }
}
</script>

<style>
</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值