VueX

55 阅读1分钟

VueX --笔记

一、Vuex概述

1、原始共享方式

  • 父子传值

    • v-bind & v-on
    <template>
      <div>
        我是子组件:
        <input type="text" :value="msg" @input="changeValFn" />
      </div>
    </template>
    <script>
    export default {
      name: 'child',
      props: ['msg'],
      methods: {
        changeValFn(e) {
          this.$emit('changeMsg', e.target.value)
        },
      },
    }
    </script>
    
    <template>
      <div class="parent">
        <h1>我是父组件:{{ msg }}</h1>
        <child :msg="msg" @changeMsg="changeMsgFn"></child>
      </div>
    </template>
    
    <script>
    import child from './child'
    export default {
      name: 'parent',
      components: {
        child,
      },
      data() {
        return {
          msg: 'hello!',
        }
      },
      methods: {
        changeMsgFn(value) {
          this.msg = value
        },
      },
    }
    </script>
    
  • 兄弟传值

    • bus
    //组件一
    bus.emit('leftChartShow')
    
    //组件二
    bus.on('leftChartShow', () => {
        this.initCharts()
    })
    

2、Vuex概述

  • Vuex是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间数据的共享。
    • 能够在vuex集中管理共享数据
    • 能够实现组件间的数据共享
    • 响应式,实时保证数据与页面的同步
  • 一般需要共享的数据存放到vuex中,不需要共享的存放到自身data

二、Vuex使用步骤

1、安装依赖

npm install vuex@3.1.2

2、新建modules文件夹

  • 根据不同需求创建不同的modules文件夹
    • 每个文件夹内部有对应这个modules的store存储
//代码内容实例如下, 例如叫moduleA.js
export default {
    namespaced: true,  //带有命名空间的模块
    state: {
        count: 0
    },
    getters: {
        showNumber(state) {
            return '当前count值为' + state.count + ''
        }
    },
    mutations: {
        add(state) {
            state.count += 1
        },
        addN(state, step) {
            state.count += step
        },
        sub(state){
            state.count -= 1
        },
        subN(state, step) {
            state.count -= step
        }
    },
    actions: {
        addAsync(context,step) {
            setTimeout(() => {
                context.commit('addN', step)
            },1000)
        }
    }
}

3、新建store.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

import moduleA from '路径地址'
import moduleB from '路径地址'

export default new Vuex.Store({
    modules: {
        moduleA,
        moduleB
    }
})

4、main.js挂载store对象

import Vue from 'vue'
import store from 'store地址'

new Vue({
    el: '#app',
    render: h => h(app),
    router,
    store // 将共享数据对象挂载到Vue实例,所有组件就可从store获取全局数据了
})

5、Vue组件使用

组件一

<template>
  <div id="app">
      <ComponentTwo></ComponentTwo>
      <hr/>
      <ComponentThree></ComponentThree>
  </div>
</template>

<script>
import ComponentTwo from './ComponentTwo'
import ComponentThree from './ComponentThree'
    
export default {
  name: 'ComponentOne',
  component: {
      ComponentTwo,
      ComponentThree
  }
}
</script>

组件二

<template>
  <div>
      <h3>当前count值:{{count}}</h3>
      <h3>{{showNumber}}</h3>
      <button @click = "add()">+1</button>
      <button @click = "addN(3)">+N</button>
      <button @click = "addAsync(5)">+1</button>
  </div>
</template>

<script>
import { mapState, mapMutations, mapActions, mapGetters } from 'vuex'
    
export default {
  name: 'ComponentTwo',
  data () {
      selfVar: 'test',
      initNum: 1
  },
  computed: {
      //mapState('模块名称', ['模块变量']),因为模块有多个,所以mapState可写多个,mapGetters同样
      ...mapState('moduleA', ['count']),   
      ...mapGetters('moduleA',['showNumber']),
      selfCompu: function () {
          return initNum + 1
      }
  },
  methods: {
      //mapMutations('模块名称',['模块变量函数']),因为模块有多个,所以mapMutations可多个,mapActions同
      ...mapMutations('moduleA',['add', 'addN']),
      ...mapActions('moduleA',['addAsync']),
      selfFunc() {
          console.log("这里写组件自己的方法")
      }
  }
}
</script>

组件三

<template>
  <div>
    <h3>当前count值: {{count}}</h3>
    <button @click = "btnSub">-1</button>
    <button @click = "btnSubN">-1</button>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
    
export default {
  name: 'ComponentThree',
  data () {
      selfVar: 'test'
  },
  computed: {
      ...mapState(['count'])
  },
  methods: {
      ...mapMutations(['sub', 'subN']),
      btnSub() {
          this.sub()
      },
      btnSubN() {
          this.subN(3)
      }
  }
}
</script>

image-20220504192134546.png