Vuex入门

Vuex是什么?

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

        可能有人不太理解这里的状态是什么,所谓“状态”,我们可以理解为数据,就是组件所渲染的“数据”。而Vuex达到的作用是数据共享,以往我们在两个有关联的组件之间传递数据时可以使用传参或者事件触发将数据从一个组件传递给另一个组件。如果单纯两个组件传递数据的话并不复杂,但当有不止一个组件需要传递数据时,简单的数据传递就比较麻烦。使用Vuex可以很好地解决这种问题,传统的被传递的数据是存在组件中的,而Vuex共享的数据是存在于store中的,当组件需要某个状态(数据)时,可以直接从store获取。我们不仅可以从store中获取数据,还可以改变store中的数据。

Vuex的安装

        在使用Vuex之前,我们需要在Vue项目中下载Vuex。

  创建Vue项目时安装

创建Vue项目时我们可以选择一些插件或配置,在这个时候我们可以选择Vuex,让脚手架帮我们在项目中安装Vuex,如下图:

cc384d0844b1428f96ab6622af7bdb1a.png

  在已存在的Vue项目中安装Vuex(vs code中)

由于我使用的是 npm 下载,所以如果想要以其他方式下载,请参考Vuex安装

        由于Vue.js与Vuex之间存在一定的依赖性,为了确保他们之间的兼容性,不同的Vue.js需要对应不同的Vuex版本。

        基于vue2下载vuex:在终端中输入以下命令

npm install vuex@3 --save

        基于vue3下载vuex:在终端中输入以下命令

npm install vuex@4 --save

创建store

Vuex的核心是store,它是应用程序的所有组件的状态的单一来源,包含了应用程序的 state、getters、mutations、actions、modules。

如果是在创建Vue项目是安装Vuex的话可以忽略这一步。

        在src目录下创建store文件夹,在store中创建index.js文件,如下图:

1adbb527ccab492bb80803ce944fcf82.png

        index.js 中:

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

Vue.use(Vuex)

export default new Vuex.Store({
    
})

        main.js 中:

import Vue from 'vue'
import App from './App.vue'
import store from './store' //导入store

Vue.config.productionTip = false

new Vue({
  store, //将store挂载到vue实例中
  render: function (h) { return h(App) },
}).$mount('#app')

Vuex的核心概念

Vuex的核心概念是state、getters、mutations、actions、modules。

  state

        state是应用中所有组件共享的唯一数据源 ,它是应用状态的容器。

        应用中所有状态集中存储在store 对象中,易于管理。状态是响应式 的,当状态更新时,依赖此状态的组件会自动更新。

        state状态保存:

const state = {
    name: '张三',
    age: 20
}

export default new Vuex.Store({
    state
})

        在组件中获取Vuex状态:

        1、在模板中直接使用:

<template>
  <div>
    <p>{{ $store.state.name }}</p>
    <p>{{ $store.state.age }}</p>
  </div>
</template>

        2、在计算属性中返回:

<template>
  <div>
    <p>{{ name }}</p>
    <p>{{ age }}</p>
  </div>
</template>
  
<script>

export default {
  name: 'App',
  computed: {
    name () {
      return this.$store.state.name
    },
    age () {
      return this.$store.state.age
    }
  }
}
</script>

        3、使用辅助函数(mapState):

<template>
  <div>
    <p>{{ name }}</p>
    <p>{{ age }}</p>
  </div>
</template>
  
<script>
import { mapState } from 'vuex'  //导入辅助函数

export default {
  name: 'App',
  computed: {
    ...mapState(['name','age']) //映射状态
  }
}
</script>

  getters

        getters可以看作vuex中的计算属性,它可以在不改变state状态的情况下计算出新的衍生状态。getters不仅可以衍生处新的状态,还可以对状态进行包装,以不同的形式返回,例如: return ‘那个男人的名字是【’ + state.name + '】'

        getters书写情况:

const getters = {
    getName(state) {
        return state.name //返回state的name
    },
    getAge(state) {
        return state.age //返回state的age
        //return state.age + 5  //返回age+5后的状态
    }
}

export default new Vuex.Store({
    state,
    getters
})

        通过getters获取Vuex状态:

        1、在模板中直接使用:

<template>
  <div>
    <p>{{ $store.getters.getName }}</p>
    <p>{{ $store.getters.getAge }}</p>
  </div>
</template>

        2、在计算属性中获取:

<template>
  <div>
    <p>{{ name }}</p>
    <p>{{ age }}</p>
  </div>
</template>
  
<script>

export default {
  name: 'App',
  computed: {
    name() {
      return this.$store.getters.getName
    },
    age() {
      return this.$store.getters.getAge
    }
  }
}
</script>

        3、使用辅助函数(mapGetters):

<template>
  <div>
    <p>{{ getName }}</p>
    <p>{{ getAge }}</p>
  </div>
</template>
  
<script>
import { mapGetters } from 'vuex' //导入辅助函数

export default {
  name: 'App',
  computed: {
    ...mapGetters(['getName','getAge'])  
  }
}
</script>

  mutations

        mutations是修改state状态的唯一方法,通过其他方式修改状态是不合法的。

        每个mutation都有一个字符串类型的事件类型和回调函数,回调函数以 state 作为第一个参数,在state后面可以添加其他参数。

        mutations写法:

const mutations = {
    setAge(state) {
        state.age ++ //使state的age加1
    }
}

export default new Vuex.Store({
    state,
    getters,
    mutations
})

        mutations的使用:

        1.使用commit触发:

<template>
  <div>
    <span>{{ getName }}---</span>
    <span>{{ getAge }}</span><br>
    <button @click="btn">点我age加1</button>
  </div>
</template>
  
<script>
import { mapGetters } from 'vuex' //导入辅助函数

export default {
  name: 'App',
  computed: {
    ...mapGetters(['getName','getAge'])  
  },
  methods: {
    btn() {
      this.$store.commit('setAge');
    }
  }
}
</script>

        2、使用辅助函数(mapMutations):

<template>
  <div>
    <span>{{ getName }}---</span>
    <span>{{ getAge }}</span><br>
    <button @click="btn">点我age加1</button>
  </div>
</template>
  
<script>
import { mapGetters,mapMutations } from 'vuex' //导入辅助函数

export default {
  name: 'App',
  computed: {
    ...mapGetters(['getName','getAge'])  
  },
  methods: {
    ...mapMutations(['setAge']),
    btn() {
      this.setAge()
    }
  }
}
</script>

  actions

        actions用于执行任意的异步操作,它不直接修改状态,它通过调用mutations来进行状态修改。actions接收context作为参数,该参数包含了commit方法。

        actions的写法:

const actions = {
    setAgeAsync(context) {
        setTimeout(() => {
            context.commit('setAge')
        },1000) //1秒后修改状态
    }
}

export default new Vuex.Store({
    state,
    getters,
    mutations,
    actions
})

        actions的使用:

        1、使用dispatch:

<template>
  <div>
    <span>{{ getName }}---</span>
    <span>{{ getAge }}</span><br>
    <button @click="btn">点我age加1</button>
    <button @click="btn2">点我1秒后age加1</button>
  </div>
</template>
  
<script>
import { mapGetters,mapMutations } from 'vuex' //导入辅助函数

export default {
  name: 'App',
  computed: {
    ...mapGetters(['getName','getAge'])  
  },
  methods: {
    ...mapMutations(['setAge']),
    btn() {
      this.setAge()
    },
    btn2() {
      this.$store.dispatch('setAgeAsync')
    }
  }
}
</script>

        2、使用辅助函数(mapActions):

<template>
  <div>
    <span>{{ getName }}---</span>
    <span>{{ getAge }}</span><br>
    <button @click="btn">点我age加1</button>
    <button @click="btn2">点我1秒后age加1</button>
  </div>
</template>
  
<script>
import { mapGetters,mapMutations,mapActions } from 'vuex' //导入辅助函数

export default {
  name: 'App',
  computed: {
    ...mapGetters(['getName','getAge'])  
  },
  methods: {
    ...mapMutations(['setAge']),
    ...mapActions(['setAgeAsync']),
    btn() {
      this.setAge()
    },
    btn2() {
      this.setAgeAsync()
    }
  }
}
</script>

  modules

        modules允许将store分割成模块化的结构,每个模块有自己的state、getters、mutations、actions。当开发大型应用时将store模块化,状态易于管理,代码容易组织和维护。

        将store模块化:

const module1 = {
    namespace: true,
    state: {
        name: '张三',
        age: 20
    },
    getters: {
        getName(state) {
            return state.name //返回state的name
        },
        getAge(state) {
            return state.age //返回state的age
            //return state.age + 5  //返回age+5后的状态
        }
    },
    mutations: {
        setAge(state) {
            state.age ++ //使state的age加1
        }
    },
    actions: {
        setAgeAsync(context) {
            setTimeout(() => {
                context.commit('setAge')
            },1000);
        }
    }
}

export default new Vuex.Store({
    modules: {
        module1 //将module1导出
    }
})

        store模块化后的使用:

<template>
  <div>
    <span>{{ name }}---</span>
    <span>{{ age }}</span><br>
    <span>{{ getName }}---</span>
    <span>{{ getAge }}</span><br>
    <button @click="btn1">点我age加1</button>
    <button @click="btn2">点我age等会加1</button>
  </div>
</template>
  
<script>
import { mapState,mapGetters,mapMutations,mapActions } from 'vuex'

export default {
  name: 'App',
  computed: {
    ...mapState('module1',['name','age']),
    ...mapGetters('module1',['getName','getAge'])
  },
  methods: {
    ...mapMutations('module1',['setAge']),
    ...mapActions('module1',['setAgeAsync']),
    btn1() {
      this.setAge();
    },
    btn2() {
      this.setAgeAsync();
    }
  }
}
</script>

总结

        Vuex是Vue.js非常重要的插件,能够更好地实现数据共享,可以通过改变状态而达到组件更新的效果。对于开发大型应用时能够更好地管理组件中的状态,代码更容易组织和维护。

相关推荐

  1. VUE 入门及应用 ( VueX )

    2024-06-15 09:08:04       17 阅读
  2. <span style='color:red;'>Vue</span><span style='color:red;'>入门</span>

    Vue入门

    2024-06-15 09:08:04      13 阅读
  3. vuex 快速入门

    2024-06-15 09:08:04       4 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-15 09:08:04       10 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-15 09:08:04       12 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-15 09:08:04       11 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-15 09:08:04       14 阅读

热门阅读

  1. 7号楼地面东照西和南照北

    2024-06-15 09:08:04       7 阅读
  2. 嵌入式linux中GPIO和Pinctrl子系统分享

    2024-06-15 09:08:04       6 阅读
  3. 双指针练习:三数之和

    2024-06-15 09:08:04       8 阅读
  4. C++ 字符串分割

    2024-06-15 09:08:04       5 阅读
  5. 2024最新前端技术趋势

    2024-06-15 09:08:04       7 阅读
  6. RichSinkFunction 在 Flink IoT 项目中的应用实战

    2024-06-15 09:08:04       4 阅读
  7. 6.2 文件的缓存位置

    2024-06-15 09:08:04       5 阅读
  8. 条件循环语句有哪些?语法?区别?

    2024-06-15 09:08:04       5 阅读
  9. C# 通过Path获取后缀,文件名,目录等

    2024-06-15 09:08:04       6 阅读