目录
  • 1、安装vuex依赖包
  • 2、导入vuex包
  • 3、创建 store 对象
  • 4、将 store 对象挂载到vue实例中
    • (1)、state:
    • (2)、mutations:
    • (3)、actions:
    • (4)、getters:

1、安装vuex依赖包

npm install vuex --save

2、导入vuex包

import vuex from 'vuex'
vue.use(vuex)

3、创建 store 对象

export default new vuex.store({
  // state 中存放的就是全局共享的数据
  state: {
    count: 0
  }
})

4、将 store 对象挂载到vue实例中

new vue({
  el: '#app',
  render: h => h(app),
  router,
  // 将创建的共享数据对象,挂载到 vue 实例中
  // 所有的组件,就可以直接用 store 中获取全局的数据了
  store
})

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

核心模块:state、mutations、actions、module、getters

在components目录下新建addition.vue文件:

<template>
<div>
  <h3>当前最新的count值为:</h3>
  <button>+1</button>
</div>
</template>

subtraction.vue文件:

<template>
<div>
  <h3>当前最新的count值为:</h3>
  <button>-1</button>
</div>
</template>

打开 app.vue 文件,引入俩个组件:

<template>
<div>
  <my-addition></my-addition>
  <p>------------------------------</p>
  <my-subtraction></my-subtraction>
</div>
</template>

<script>
import addition from './components/addition'
import subtraction from './components/subtraction'
export default {
  components: {
    'my-addition': addition,
    'my-subtraction': subtraction
  },
  data () {
    return {}
  }
}
</script>

(1)、state:

state 提供唯一的公告数据源,所有共享的数据都要统一放到 store 的 state 中进行存储。我们需要保存的数据就保存在这里,可以在页面通过 this.$store.state来获取我们定义的数据。

// 创建store数据源,提供唯一公共数据
const store = new vuex.store({
   state: {
      count: 0
   }
})

组件访问 store 中数据的第一种方式:

this.$store.state.全局数据名称

组件访问 store 中数据的第二种方式:

// 1.从 vuex 中按需导入 mapstate 函数
import { mapstate } from 'vuex'

通过刚才导入的 mapstate 函数,将当前组件需要的全局数据,映射为当前组件的 computed 计算属性:

// 2.将全局数据,映射为当前组件的计算属性
computed: {
    ...mapstate(['count'])
}

打开store/index.js文件,定义 count:

import vue from 'vue'
import vuex from 'vuex'

vue.use(vuex)

export default new vuex.store({
  state: {
    count: 0
  },
  mutations: {
  },
  actions: {
  },
  modules: {
  }
})

回到addition.vue文件中,用第一种方式:

<template>
<div>
  <h3>当前最新的count值为:{{$store.state.count}}</h3>
  <button @click="handleadd">+1</button>
</div>
</template>

回到 subtraction.vue文件中,用第二种方式:

<template>
<div>
  <h3>当前最新的count值为:{{count}}</h3>
  <button>-1</button>
</div>
</template>

<script>
import { mapstate } from 'vuex'
export default {
  data () {
    return {}
  },
  // 计算属性
  computed: {
    ...mapstate(['count']) // 用...展开运算符把count展开在资源属性里
  }
}
</script>

此时效果图:

(2)、mutations:

mutations 用于变更 store 中的数据。只有 mutation里的函数才有权利去修改state中的数据。mutation非常类似于事件:每个 mutation 都有一个字符串的事件类型 (type)和 一个回调函数 (handler)。但是,mutation只允许同步函数,不能写异步的代码。

  • ①只能通过 mutation 变更 store 数据,不可以直接操作 store 中的数据。
  • ②通过这种方式虽然操作起来稍微繁琐一些,但是可以集中监控所有数据的变化。

定义:

// 定义 mutation
const store = new vuex.store({
  state: {
    count: 0
  },
  mutations: {
    add (state) {
      // 变更状态
      state.count++
    }
  }
})

第一种触发方式:

// 触发 mutation
methods: {
    handleadd () {
      // 触发 mutations 的第一种方式
      this.$store.commit('add')
    }
}

打开store/index.js文件,定义mutations :

mutations: {
    add (state) {
      state.count++
    }
}

回到 addition.vue文件中触发:

<template>
<div>
  <h3>当前最新的count值为:{{$store.state.count}}</h3>
  <button @click="handleadd">+1</button>
</div>
</template>

<script>
export default {
  methods: {
    handleadd () {
      this.$store.commit('add')
    }
  }
}
</script>

此时点击+1按钮,就可以看到数值变为1。

还可以在触发 mutations 时传递参数:

// 定义 mutation
const store = new vuex.store({
  state: {
    count: 0
  },
  mutations: {
    addn (state, step) {
      // 变更状态
      state.count += step
    }
  }
})

第一种触发方式:

// 触发 mutation
methods: {
    handleadd () {
      this.$store.commit('addn', 3)
    }
}

打开store/index.js文件,增加一个addn:

mutations: {
    add (state) {
      state.count++
    },
    addn (state, step) {
      state.count += step
    }
}

回到 addition.vue文件中,增加一个+n的按钮并增加点击事件:

<template>
<div>
  <h3>当前最新的count值为:{{$store.state.count}}</h3>
  <button @click="handleadd">+1</button>
  <button @click="handleadd2">+n</button>
</div>
</template>

<script>
export default {
  data () {
    return {
      num: 2
    }
  },
  methods: {
    handleadd () {
      this.$store.commit('add')
    },
    handleadd2 () {
      // commit 的作用,就是调用某个 mutation 函数
      this.$store.commit('addn', this.num)
    }
  }
}
</script>

此时点击+n按钮就会每次增加2。

触发 mutations 的第二种方式:

// 1.从 vuex 中按需导入 mapmutations 函数
import { mapmutations } from 'vuex'

通过刚才导入的 mapmutations 函数,将需要的 mutations 函数,映射为当前组件的 methods 方法:

// 2.将指定的 mutations 函数,映射为当前组件的methods 函数:
methods: {
   ...mapmutations({'add', 'addn'})
}

打开store/index.js文件,在mutations增加一个sub:

mutations: {
    add (state) {
      state.count++
    },
    addn (state, step) {
      state.count += step
    },
    sub (state) {
      state.count--
    }
},

回到 subtraction.vue文件中,给-1按钮增加点击事件:

<template>
<div>
  <h3>当前最新的count值为:{{count}}</h3>
  <button @click="handlesub">-1</button>
</div>
</template>

<script>
import { mapstate, mapmutations } from 'vuex'
export default {
  data () {
    return {}
  },
  // 计算属性
  computed: {
    ...mapstate(['count']) // 用...展开运算符把count展开在资源属性里
  },
  methods: {
    ...mapmutations(['sub']),
    handlesub () {
      this.sub()
    }
  }
}
</script>

这时刷新页面,点击-1按钮就会每次-1了。

打开store/index.js文件,增加一个subn:

mutations: {
    add (state) {
      state.count++
    },
    addn (state, step) {
      state.count += step
    },
    sub (state) {
      state.count--
    },
    subn (state, step) {
      state.count -= step
    }
},

回到subtraction.vue文件中,在增加一个-n的按钮,并添加点击事件:

<button @click="handlesub2">-n</button>

<script>
import { mapstate, mapmutations } from 'vuex'
export default {
  methods: {
    ...mapmutations(['sub', 'subn']),
    handlesub () {
      this.sub()
    },
    handlesub2 () {
      this.subn(2)
    }
  }
}
</script>

这时点击-n按钮,每次就-2了。

下面有个需求,就是在点击+1按钮后延迟1秒在显示变化后的数值。

注意:不要在mutations函数中,执行异步操作。所以就需要用到了action用于处理异步任务。

(3)、actions:

action 用于处理异步任务。

如果通过异步操作变更数据,必须通过 action,但是在 action 中还是要通过触发 mutation 的方式间接变更数据。

定义:

// 定义 action
const store = new vuex.store({
  // ...省略其他代码
  mutations: {
    add (state) {
      state.count++
    }
  },
  actions: {
    addasync (context) {
      settimeout(() => {
        context.commit('add')
      }, 1000)
    }
  }
})

第一种方式触发:

// 触发 action
methods: {
  handleadd () {
      // 触发 actions 的第一种方式
      this.$store.dispatch('addasync')
  }
}

打开store/index.js文件,增加一个 addasync:

actions: {
    addasync (context) {
      settimeout(() => {
        // 在 actions 中,不能直接修改 state 中的数据
        // 必须通过 context.commit() 触发某个 mutations 的函数才行
        context.commit('add')
      }, 1000)
    }
}

回到 addition.vue文件中,增加一个+1 async的按钮并增加点击事件:

<button @click="handleadd3">+1 async</button>

<script>
export default {
  methods: {
    handleadd () {
      this.$store.commit('add')
    },
    handleadd2 () {
      // commit 的作用,就是调用某个 mutation 函数
      this.$store.commit('addn', this.num)
    },
    handleadd3 () {
      this.$store.dispatch('addasync')
    }
  }
}
</script>

这时点击+1 async按钮,可以实现延迟1秒后+1的功能了。

触发 actions 异步任务时携带参数:

定义:

// 定义 action
const store = new vuex.store({
  // ...省略其他代码
  mutations: {
    addn (state, step) {
      state.count += step
    },
  },
  actions: {
    addnasync (context, step) {
      settimeout(() => {
        context.commit('addn', step)
      }, 1000)
    }
  }
})

触发:

// 触发 action
methods: {
  handleadd () {
      // 在调用 dispatch 函数,触发 actions 时携带参数
      this.$store.dispatch('addnasync', 5)
  }
}

打开 store/index.js 文件,增加一个 addnasync: 

actions: {
    addasync (context) {
      settimeout(() => {
        // 在 actions 中,不能直接修改 state 中的数据
        // 必须通过 context.commit() 触发某个 mutations 的函数才行
        context.commit('add')
      }, 1000)
    },
    addnasync (context, step) {
      settimeout(() => {
        context.commit('addn', step)
      }, 1000)
    }
}

回到 addition.vue 文件中,增加一个+n async的按钮并增加点击事件:

<button @click="handleadd4">+n async</button>

<script>
export default {
  methods: {
    handleadd4 () {
      // 在调用 dispatch 函数,触发 actions 时携带参数
      this.$store.dispatch('addnasync', 5)
    }
  }
}
</script>

这时点击+n async按钮,可以实现延迟1秒后+5的功能。

触发 actions 的第二种方式:

// 1.从 vuex 中按需导入 mapactions 函数
import { mapactions } from 'vuex'

通过刚才导入的 mapactions 函数,将需要的 actions 函数,映射为当前组件的 methods 方法:

// 2.将指定的 actions 函数,映射为当前组件的 methods 函数
methods: {
  ...mapactions(['addasync', 'addnasync'])
}

打开 store/index.js 文件,在 actions 增加一个 subasync:

actions: {
    addasync (context) {
      settimeout(() => {
        // 在 actions 中,不能直接修改 state 中的数据
        // 必须通过 context.commit() 触发某个 mutations 的函数才行
        context.commit('add')
      }, 1000)
    },
    addnasync (context, step) {
      settimeout(() => {
        context.commit('addn', step)
      }, 1000)
    },
    subasync (context) {
      settimeout(() => {
        context.commit('sub')
      }, 1000)
    }
}

回到 subtraction.vue 文件中,在增加一个-1 async的按钮,并添加点击事件:

<button @click="handlesub3">-1 async</button>

<script>
import { mapstate, mapmutations, mapactions } from 'vuex'
export default {
  methods: {
    ...mapmutations(['sub', 'subn']),
    ...mapactions(['subasync']),
    handlesub () {
      this.sub()
    },
    handlesub2 () {
      this.subn(2)
    },
    handlesub3 () {
      this.subasync()
    }
  }
}
</script>

还有个更简单的方式:

<button @click="subasync">-1 async</button>

<script>
import { mapstate, mapmutations, mapactions } from 'vuex'
export default {
  methods: {
    ...mapactions(['subasync'])
  }
}
</script>

这样实现的效果是一样的。

下面用同样的思路来实现-n的异步操作:

打开 store/index.js 文件,增加一个 subnasync: 

actions: {
    subnasync (context, step) {
      settimeout(() => {
        context.commit('subn', step)
      }, 1000)
    }
}

回到 subtraction.vue 文件中,在增加一个-n async的按钮:

<button @click="subnasync(3)">-n async</button>

<script>
import { mapstate, mapmutations, mapactions } from 'vuex'
export default {
  methods: {
    ...mapactions(['subasync', 'subnasync'])
  }
}
</script>

这时点击-n async按钮,可以实现延迟1秒后-3的功能。

(4)、getters:

getter 用于对 store 中的数据进行加工处理形成新的数据。不会修改 state 里的源数据,只起到一个包装器的作用,将 state 里的数据变一种形式然后返回出来。
① getter 可以对 store 中已有的数据加工处理之后形成新的数据,类似vue的计算属性。
② store 中数据发生变化,getter 包装出来的数据也会跟着变化。

定义:

// 定义 getter
const store = new vuex.store({
  state: {
    count: 0
  },
  getters: {
    shownum: state => {
      return '当前最新的数量是【'+ state.count +'】'
    }
  }
})

使用 getters 的第一种方式:

this.$store.getters.名称

我们可以把文字的内容删除掉,然后用 getters 来替换:

打开 store/index.js 文件,定义getters:

getters: {
    shownum (state) {
      return '当前最新的数量是【' + state.count + '】'
    }
}

回到 addition.vue 文件修改:

<h3>{{$store.getters.shownum}}</h3>

此时刷新页面,已经变为了 getters 中的内容,效果图:

使用 getters 的第二种方式:

import { mapgetters } from 'vuex'

computed: {
  ...mapgetters(['shownum'])
}

打开 subtraction.vue 文件修改:

<h3>{{shownum}}</h3>

<script>
import { mapstate, mapmutations, mapactions, mapgetters } from 'vuex'
export default {
  // 计算属性
  computed: {
    ...mapstate(['count']), // 用...展开运算符把count展开在资源属性里
    ...mapgetters(['shownum'])
  }
}
</script>

效果图:

到此这篇关于vuex安装及使用基础教程的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持www.887551.com。