vuex 学习一

vuex 学习一,第1张

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

具体可以学习:Vuex官网

初始化一个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

在项目src目录下新建一个store文件夹,在store下新建一个index.js 索引文件,用于管理store下所有的子模块在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: ''
})
在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', 'Bbanana', '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

定义好了store , 在具体的组件实例中怎么用呢?

<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中的变量经过2次处理然后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']),
    // 2中写法,一种是数组的形式,
    // 一种是对象的形式,对象可以起别名
    // ...mapState(['counter']),
    ...mapState({
      myCounter: 'counter' // 相当于给counter起了一个别名,这样就直接可以使用 c 来代替counter
    }),
    ...mapState('products', ['list'])
  },
  methods: {
    // products 表示模块名, add 表示方法名。 即 products 模块下的 add 方法
    ...mapMutations('products', ['add']),
    ...mapActions('products', ['addAsync']), // 异步方法
    
    handleKeyUp (e) {
      if (e.currentTarget.value) {
        this.add(e.currentTarget.value)
      }
    },
    addDelay () {
      this.addAsync(this.text)
    }
  }
}
</script>

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1320147.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-11
下一篇2022-06-11

发表评论

登录后才能评论

评论列表(0条)

    保存