美文网首页
VUE-VUEX的使用

VUE-VUEX的使用

作者: 晴天3521 | 来源:发表于2020-01-14 22:50 被阅读0次
  • 安装vuex
npm install vuex --save / cnpm install vuex --save
  • 在store.js页面引入
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
  • 定义数据
// 1.state 表示状态 用于存储数据
var state = {
    count:1
}
// 2.mutations里面放的是方法,主要用于改变state里面的数据
var mutations = {
    addNum(){
        ++state.count;
    }
}
// 3.类似计算属性 改变state里面的count数据的时候 会触发getters里面的方法 获取新的值
var getters = {
    computedCount:(state)=>{
        return state.count*2
    }
}
//  4.action 提交的是mutation,而不是直接变更状态,包含任意的异步操作
var actions ={
    addMutationsCount(context){ // 调用context.commit 提交一个mutation
        context.commit('addNum') // 执行mutations里面的 addNum方法 改变state里面的数据
    }
}
  • 暴露 vuex 实例化
const  store = new Vuex.Store({
    state,
    mutations,
    getters,
    actions
})
export default store;
  • 组件内使用
import store from '../vuex/store.js'
  • 注册
export default {
  name: "Home",
  data() {
    return {
      msg: "你好",
    }
  },
  store,
  methods: {
    addCount(){
      // 改变vuex store里面的数据
      this.$store.commit('addNum') // 触发state里面的数据
    }
  }
};
  • 获取state里面的数据
this.$store.state.count
  • 触发mutations 改变state里面的数据
this.$store.commit('addNum') // 触发state里面的数据
  • 触发actions里面的方法
this.$store.dispatch('addMutationsCount') 
  • 获取getters里面的数据
this.$store.getters.computedCount

好了,今天的分享就到这里了!
愿你三冬暖,愿你春不寒;愿你天黑有灯,下雨有伞。


小晴天

相关文章

  • VUE-VUEX的使用

    安装vuex 在store.js页面引入 定义数据 暴露 vuex 实例化 组件内使用 注册 获取state里面的...

  • vue-vuex

    事件总线 Vue.prototype.bus = new Vue()console.log(this.bus)子组...

  • vue-vuex

    欢迎访问我的博客https://qqqww.com/,祝码农同胞们早日走上人生巅峰,迎娶白富美~~~ 描述 本文档...

  • vue-vuex的namespaced-使用watch监听sta

    使用 module,不使用 namespaced 情况: 可能存在重复的action或者mutation vue组...

  • Vue-vueX(十一)

    1、什么是vuex? Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所...

  • vue-vuex缓存

    缓存vuex数据并加密。

  • vue-vuex简单介绍

    vuex的应用场景,就是多个组件之间相互传值 创建项目选择router和vuex 打开src/store/inde...

  • (Vue全家桶)Vue-vuex

    vuex入门 vuex是一个专门为vue.js设计的集中式状态管理架构。状态?我把它理解为在data中的属性需要共...

  • vue-vuex与react redux 比较

    vuex store的目录结构 模块结构 辅助映射函数 mapState, mapGetters, mapM...

  • iconfont的使用(下载使用)

    1、下载文件 2、在生命周期中引入项目 beforeCreate () { var domModule = ...

网友评论

      本文标题:VUE-VUEX的使用

      本文链接:https://www.haomeiwen.com/subject/dkczactx.html