入门vue-VueX

Vue干货 小白 暂无评论

 vuex有4个重要的属性

  1. state

  2. getter

  3. mutations

  4. actions

其中state类似于初始化,说明里面有那些数据

getter是读取数据库里面的数据,但是使用showState来获取数据,因而是只读的,不会对数据有任何的影响

mutations是真正的修改数据

而外界通过actions的commit,从而调用mutation,实现修改数据

所以流程大致就是这样

定义一个文件夹store,新建一个store.js文件

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
 state: {
   showSignin: true
 },
 mutations: {
   SHOW_SIGNIN (state) {
     state.showSignin = !state.showSignin
   }
 },
 actions: {
   showSignin ({ commit }) {
     commit('SHOW_SIGNIN')
   }
 },
 getters: {
   showState: function (state) {
     return state.showSignin
   }
 }
})

在main.js里面引入store.js的store, 因为es6的原因,可以直接用store替换store:store

import store from './store/store'
new Vue({
 el: '#app',
 router,
 store,
 template: '<App/>',
 components: { App }
})

外界调用store,比如在signin.vue里面按下登陆按钮,执行doSignin method,这个函数调用store里面的showSignin方法

<a type="submit" class="btn btn-success" @click="doSignin"> 登录 </a>
scrpit方法
methods: {
   doSignin (e) {
     this.$store.dispatch('showSignin')
   }
}

获取store里面的数据

<li><p v-if="showSignin">{{welcome}}</p></li>
<script>
export default {
 name: 'navBar',
 data () {
   return {
     welcome: 'welcome'
   }
 },
 computed: {
   showSignin () {
     return this.$store.getters.showState
   }
 }
}
</script>

可以用chrome的扩展工具vue-devTool来查看数据的变化 
       点击按钮, compute计算showSignIn的值会发生变化

可以用vue-devTool的time travel来实时查看数据,还可以revert到之前的状态

 

 

转载请注明: Vue教程中文网 - 打造国内领先的vue学习网站-vue视频,vue教程,vue学习,vue培训 » 入门vue-VueX

喜欢 ()or分享