nuxt项目中使用store

首先初始化创建一个nuxt项目

nuxt项目创建以后,内部已自动集成store,所以无需再单独安装和引入

在根目录的store文件夹下新建文件,例如home.js

//home.js
export const state = () => ({
    age: 18
})
 
export const mutations = {
    add(state, data) {
        state.age += data
    }
}
 
export const actions = {
    addAge(store, data) {
        console.log(store);
        setTimeout(() => {
            store.commit('add', data)
            console.log(store.state.age);
        }, 2000)
    }
}
 
export const getters = {
 
}

  在页面中访问

  methods: {
    add() {
      // this.$store.state.home.name;
      // this.$store.commit("home/add", 2);
      this.$store.dispatch("home/addAge", 2);
    },
  },

  asyncData中访问

async asyncData ({ app, $axios, params, store }) {
  return {
age:store.state.home.age
}
}

  

posted @ 2022-07-26 11:13  枫若  阅读(938)  评论(0编辑  收藏  举报