XiaoShang

  • 笔记
  • 日志
  • 阅读
所有文章

XiaoShang

  • 笔记
  • 日志
  • 阅读

学习使用Vuex

2018-02-11 11:16:01

1、如何创建一个vuex实例?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
}
})

export { store as default }

这样就创建了一个简单的Vuex实例store,这个实例有两个属性:state 和 mutations
state: 用于存储各种状态,类似Vue组件中的data
mutations: 存储方法,用于修改state中的各种状态(变量),类似于Vue组件中的methods

2、如何在Vue组件中使用state 和 mutations ?

首先声明一个组件Counter.vue组件

1
2
3
4
5
6
<template>
<div>
<div>counted {{ count }}</div>
<button @click="increment">+</button>
</div>
</template>

这个组件模版依赖一个count变量,和一个 increment 函数。
对于count的值,会使用前面声明的Vuex实例的state属性中的count的值。
对于increment 函数,会使用前面声明的Vuex实例的mutations属性中的increment函数。

Tip: 记得在main.js中导入上面声明的store, 并从根组件“注入”到每一个子组件中

1
2
3
4
5
6
7
8
import store from '@/store'

new Vue({
el: '#app',
store, // 注入store,这样在所有组件都可以使用this.$store获取实例
components: { App },
template: '<App/>'
})

Counter.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
export default {
computed: {
count() {
// 想要在组件中使用Vuex实例中的state,只需在computed属性中返回所需的状态即可
return this.$store.state.count
}
},
methods: {
increment() {
// 想要在组件中使用Vuex实例中的mutations,只需调用this.$store.commit(),参数是字符串,对应想要使用的mutations
this.$store.commit('increment')
}
}
}

3、mapState 辅助函数是什么、有什么用、如何用?

  1. mapState 是一个辅助函数
  2. 帮我们生成计算属性
  3. 用法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
computed: mapState({
// 箭头函数可使代码更简练
// 第1种用法,传入state作为参数,返回了state.count,这样就获取了store中的count
count: state => state.count,

// 传字符串参数 'count' 等同于 `state => state.count`
// 第2种用法,与第1种用法只是写法不同,现在可以在模版种使用变量countAlias, 值与count相同
countAlias: 'count',

// 为了能够使用 `this` 获取局部状态,必须使用常规函数
// 第3种用法,使用常规函数,这样就可以使用this获取组件的局部状态
countPlusLocalState (state) {
return state.count + this.localCount
}
})
  • Vue
  • note

扫一扫,分享到微信

微信分享二维码
一个基于vue的图片轮播组件的实现
git如何删除commit点
  1. 1. 1、如何创建一个vuex实例?
  2. 2. 2、如何在Vue组件中使用state 和 mutations ?
  3. 3. 3、mapState 辅助函数是什么、有什么用、如何用?

Gitalking ...

© 2019 XiaoShang
  • 所有文章

tag:

  • JS
  • Mac
  • Npm
  • Redis
  • MySql
  • AngularJS
  • HTML
  • CSS
  • Hexo
  • Git
  • Vue
  • Linux
  • Node
  • Nginx
  • Canvas

    缺失模块。
    1、请确保node版本大于6.2
    2、在博客根目录(注意不是yilia根目录)执行以下命令:
    npm i hexo-generator-json-content --save

    3、在根目录_config.yml里添加配置:

      jsonContent:
        meta: false
        pages: false
        posts:
          title: true
          date: true
          path: true
          text: false
          raw: false
          content: false
          slug: false
          updated: false
          comments: false
          link: false
          permalink: false
          excerpt: false
          categories: false
          tags: true