码迷,mamicode.com
首页 > 其他好文 > 详细

vuex

时间:2018-03-30 14:15:00      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:保存   temp   异步   需要   col   actions   color   var   data   

main.js

npm i vuex --save

import Vuex from ‘vuex‘

import store from ‘./store‘

Vue.use(Vuex)

new Vue({
    el: ‘#app‘,
    router,
    store,
    components: {
        App
    },
    template: ‘<App/>‘
})

 

 

 

 然后  建一个store.js   为了保存 你的状态呀

 

store.js 

import Vue from ‘vue‘
import Vuex from ‘vuex‘

// 告诉 vue “使用” vuex
Vue.use(Vuex)

// 创建一个对象来保存应用启动时的初始状态
// 需要维护的状态
const store = new Vuex.Store({
    state: {
        
    },
    mutations: {
        
    },
    getters: {
        
    },
    actions: {
    
    }
})
// 整合初始状态和变更函数,我们就得到了我们所需的 store
// 至此,这个 store 就可以连接到我们的应用中
export default store

 

status  获取状态

this.$store.state   就是 你的 state   获取值

 

getters 获取

store.js

import Vue from ‘vue‘ import Vuex from ‘vuex‘ // 告诉 vue “使用” vuex Vue.use(Vuex) // 创建一个对象来保存应用启动时的初始状态 // 需要维护的状态 const store = new Vuex.Store({ state: { age: 55 }, getters: { getAge: function(state) { return state.age; } }, }) // 整合初始状态和变更函数,我们就得到了我们所需的 store // 至此,这个 store 就可以连接到我们的应用中 export default store

store.vue
computed:{
         name:function(){

           return this.$store.getters.getAge

         }

 



 

Mutation  改变state 中的值   同步

store.js

mutations: {
        change: function(s, c) {
            s.age = c
        }
    }

store.vue

    methods:{
         jia:function(){
             var data=this.$store.state.age+1

              this.$store.commit(‘change‘,data)

              console.log(this.$store.state.age)
         }
     }

 

actions 异步改变值

 

store.js

const store = new Vuex.Store({ state: { age: 55 }, mutations: { yibu: function(s, c) { s.age = c } }, actions: { jian: function(context, value) { console.log(context) console.log(value) setTimeout(function() {           context.commit(‘yibu‘, value); }, 1000) } } })

store.vue
   methods:{
         jian:function(){
             var data=this.$store.state.age-1

              this.$store.dispatch(‘jian‘, 5);

              console.log(this.$store.state.age)
         }
     }

 

 

 

vuex

标签:保存   temp   异步   需要   col   actions   color   var   data   

原文地址:https://www.cnblogs.com/nns4/p/8675690.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!