首页 > 其他 > 详细

vuex

时间:2018-03-30 13:55:51      阅读:200      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!