vuex 学习一

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 + 库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化

具体可以学习:Vuex官网
在这里插入图片描述

  1. 初始化一个vue项目
// (1) 安装vue-cli 脚手架
		npm install -g @vue/cli
// (2) 初始化 vue 项目
		vue init webpack vuex-app
// (3) 启动项目
		npm run dev
// 如果发现无法使用vuex 并且terminal 出现一下信息,这是因为vue和vuex的版本不兼容,需要升级vuex
// vue版本2.0要对应vuex版本3.0 如果是vue2.0版本,安装了vuex4.0版本,把vuex降级
// vue版本3.0要对应vuex版本4.0
		npm install --save vuex@3.6.2

vue版本和vuex版本不兼容警告提示

  1. 在项目src目录下新建一个store文件夹,在store下新建一个index.js 索引文件,用于管理store下所有的子模块
  2. 在main.js 入口文件中引入并挂载 store 实例
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store' // 引入store 模块

Vue.config.productionTip = false
// eslint-disable-next-line no-new
new Vue({
  el: '#app',
  router,
  store, // 挂载 store至 vue实例上
  components: { App },
  template: '<App/>'
})
  1. 在index.js 中:
import Vuex from 'Vuex'
import Vue from 'vue'
import products from './modules/products' // 导入 products 模块

Vue.use(Vuex)
// 创建store 实例
const store = new Vuex.Store({
  state: {
    counter: 1,
    app: 'vuex-app' // 项目的名称
  },
  // 一个单独的模块包含state, mutations, actions, getters 这些内容
  modules: {
    products: {
      namespaced: true,
      state: {
        list: ['Apple', 'Banana', 'Peach', 'Grape']
      },
      // 所有对state的操作的方法都放在mutations中
      mutations: {
        // state 表示当前模块的数据
        // payload 表示参数
        add (state, payload) {
          state.list.push(payload)
        }
      },
      // 异步操作
      actions: {
        // 所有的异步操作都在actions中
        // context 环境变量
        addAsync (context, payload) {
          setTimeout(() => {
            // context.state.list.push(payload) // 这样直接改变state不会被dev-tools 追踪到变化,不建议这样做
            context.commit('add', payload) // commit 表示触发一个mutation
          }, 1000)
        },
        // 还有一种写法一般将 commit 从 context对象中解构出来
        // addAsync ({commit}, payload) {
			// setTimeout(() => {
				// commit('add', payload)
			// }, 1000)
		// }
      }
    }
  }
})
export default store

打印context
context

  1. 定义好了store , 在具体的组件实例中怎么用呢?
<!--HelloWorld.vue-->
<template>
  <div class="hello">
    <!-- {{ $store.state.count }} 这种方式不推荐-->
    <p>{{ myCounter }}</p>
    <ul>
      <li v-for="(item, index) in list" :key="index">{{item}}</li>
    </ul>
    <input type="text" v-model="text" placeholder="请输入" @keyup.enter="handleKeyUp" />
    <button @click="addDelay">新增</button>
  </div>
</template>
<script>
// mapState 将 vuex 中的 state 中的数据映射到 computed
// mapGetters 相当于计算属性,就是将 state 中的变量经过处理然后return
// mapMutations 将 vuex 中的 mutations 映射到 methods
// mapActions 将 vuex 中的 actions 映射到 methods
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'

export default {
  name: 'HelloWorld',
  data () {
    return {
      text: ''
    }
  },
  computed: {
  	...mapGetters(['getSortedData', 'getStringData', 'getHandledData']),
    // 两中写法,一种是数组的形式,一种是对象的形式,对象可以起别名
    // ...mapState(['counter']),
    ...mapState({
      myCounter: 'counter' // 相当于给counter起了一个别名 myCounter,这样就直接可以使用 myCounter 来代替counter
    }),
    ...mapState('products', ['list'])
  },
  methods: {
    // products 表示模块名, add 表示方法名。 即 products 模块下的 add 方法
    ...mapMutations('products', ['add']),
    ...mapActions('products', ['addAsync']), // 异步方法
    
    /**
    * 对象的写法:
	* ...mapMutations({addMethod: 'products/add'})
	* ...mapActions({addApi: 'products/addAsync'})
	**/
    handleKeyUp (e) {
      if (e.currentTarget.value) {
        this.add(e.currentTarget.value)
      }
    },
    addDelay () {
      this.addAsync(this.text)
    }
  }
}
</script>
<style scoped>
</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值