vue+vuex组件化实践

2017-07-03  本文已影响0人  adtk

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
上一篇 下一篇

猜你喜欢

热点阅读