nuxt中store

nuxt中store的介绍使用

1.store详解nuxt内置了vuex,如果我们创建了store目录,nuxt会自动处理vuex,我们只需要在store目录中创建要使用的js文件即可

// 我们可以创建很多的使用的js文件,官方建议有一个主入口js,剩下的是配合主入口文件完成响应的功能

// store/user.js
export const state = () => ({
    userInfo: []
})

export const mutations = {
    add (state, object) {
        state.userInfo.push(object)
    }
}

export const actions = {
    getData (store) {
        setTimeout(() => {
            store.commit('add')
        }, 3000)
    }
}


// store/storage.js
// 本地存储一些基本数据
export const state = () => ({
    
})

export const mutations = {
   
}

export const actions = {
    
}



// 在页面中使用

console.log(this.$store.state.user.userInfo)    // 注意user是js文件名字,调用方法或者初始化数据的时候,要加上路径从哪个文件中使用

const userInfo = {
      name: '小美',
      age: '20',
      sex: '女',
      id: 5
}

// 意思使用的是userjs文件下的addff
 this.$store.commit('user/add', userInfo)

// 执行异步方法的调用
this.$store.dispatch('user/getData')
原文地址:https://www.cnblogs.com/zxuedong/p/12550254.html