vuex
不错的教程:
在按上面的教程搭建项目的过程中,有遇到小面的问题:
1.提示Extra semicolon
错误
参考:
在.eslintrc.js
中的rules
添加"semi": ["error", "always"],
在webpack.base.conf.js
中注释掉如下的内容:
const createLintingRule = () => ({
// test: /\.(js|vue)$/,
// loader: 'eslint-loader',
// enforce: 'pre',
// include: [resolve('src'), resolve('test')],
// options: {
// formatter: require('eslint-friendly-formatter'),
// emitWarning: !config.dev.showEslintErrorsInOverlay
// }
})
vuex属于vue生态的一部分,记录下使用过程中遇到的问题
1.mapState
、mapActions
在看别人源码的过程中,有组件中有看到这样使用,如下:
<script>
import {mapState, mapActions} from 'vuex'
export default {
data(){
return{
}
},
mounted(){
//获取用户信息
this.getUserInfo();
},
props: ['signinUp', 'headTitle', 'goBack'],
computed: {
...mapState([
'userInfo'
]),
},
methods: {
...mapActions([
'getUserInfo'
]),
},
}
</script>
参考:
- 理解Vuex的辅助函数mapState, mapActions, mapMutations用法
- 理解Vuex,看这篇就够了
- 一、介绍 vuex里面的四大金刚:State, Mutations,Actions,Getters
Vuex运行机制
核心概念
- State - this.$store.state.xxx 取值
- Getter - this.$store.getters.xxx 取值
- Mutation - this.$store.commit(“xxx”)赋值
- Action - this.$store.dispatch(“xxx”)赋值
- Module
底层原理
- State - 提供一个响应式数据
- Getter - 借助Vue的计算属性computed来实现缓存
- Mutation - 更改state方法
- Action - 触发mutation方法
- Module - Vue.set动态添加state到响应式数据中
Vuex最佳实践
1.使用常量替代Mutation
事件类型
将事件类型放到一个单独的文件中,非常方便团队协作
2.Module
- 开启命名空间
namespaced:true
- 嵌套模块不要过深,尽量扁平化
- 灵活应用createNamespacedHelpers