vue+vuex组件化实践

vuex:我的简单理解就是 ‘在各个组件中共享数据’

此项目是基于vue-cli的webpack的简单例子

//main.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)  //装载vuex
import App from './App.vue' //组件
const store = new Vuex.Store({//定义在vue实例化之前
  state: {  //状态,就是需要共享的数据,备注一
    count: 0
  },
  mutations: {  //改变store 中状态(数据)的唯一方法是 调用 mutations中定义的方法
    increment (state,data) {//备注二
      state.count++;
      console.log(store.state.count)
    },
    increment2 (state,data) {//state就是store中的state(不用理会),data是传进来的值
      state.count++;
      console.log(store.state.count)
    }
  }
})

//实例化vue
new Vue({
  el: '#app',
  store,  //若要在子组件中使用vuex,添加此属性store:store
  render: h => h(App)
})

备注一:在组件中获取state中的值,需要vue计算属性,在html中直接用属性{{count}}
下面第二张图在组件中需要: import { mapState } from 'vuex'

挨个引入共享属性
将需要引入的属性加入数组

备注二:
普通提交mutation使用方法:store.commit('increment',data);'increment'是mutations中的方法名,data是传进去的值
在.vue的等组件中使用,需要vue实例化时添加store属性,
在组件中调用方法见下图
下面第二张图需要: import { mapMutations } from 'vuex'

在组件中用的方法
多个mutation或者多出调用时使用更简单的
// 组件App.vue
<template>
    <div id="app2"><!--只能一个根元素-->
        <div v-on:click="click_a" class="hello">hello {{msg}}</div>
        <div>{{count}}</div>
    </div>
</template>
<script>
import { mapMutations } from 'vuex'
export default {
    data() {
        return {
            msg: "Vue",
        }
    },
    methods: {
        ...mapMutations(["increment"]),
        click_a() {
            this.increment()
             //   this.$store.commit('increment');
        }
    },
    computed: {
        count() {
            return this.$store.state.count
        }
    }
}
</script>

<style>
.hello {}
</style>

问题:
1,遇到 转译:‘...’失败问题
npm install babel-preset-stage-0
在.babelrc文件presets中添加stage-0,

{
  "presets": ["stage-0"]
}```

此文记录我学习的两个重要的基本用法,

原文:https://vuex.vuejs.org/zh-cn/state.html
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Vuex是什么? Vuex 是一个专为 Vue.js应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件...
    萧玄辞阅读 3,154评论 0 6
  • vuex 场景重现:一个用户在注册页面注册了手机号码,跳转到登录页面也想拿到这个手机号码,你可以通过vue的组件化...
    sunny519111阅读 8,041评论 4 111
  • 安装 npm npm install vuex --save 在一个模块化的打包系统中,您必须显式地通过Vue.u...
    萧玄辞阅读 2,970评论 0 7
  • vuex是什么鬼? 如果你用过redux就能很快的理解vuex是个什么鬼东西了。他是vuejs用来管理状态的插件。...
    麦子_FE阅读 6,903评论 3 37
  • 译文地址Vuex basics: Tutorial and explanation 更新于2016年11月:这篇文...
    莫莫小熊阅读 1,211评论 0 2