nuxt项目中使用store

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

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//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 = {
  
}

  在页面中访问

1
2
3
4
5
6
7
methods: {
  add() {
    // this.$store.state.home.name;
    // this.$store.commit("home/add", 2);
    this.$store.dispatch("home/addAge", 2);
  },
},

  asyncData中访问

1
2
3
4
5
async asyncData ({ app, $axios, params, store }) {
  return {
age:store.state.home.age
}
}

  

posted @   枫若  阅读(1000)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类
历史上的今天:
2021-07-26 vue-i18n ,vue项目中如何实现国际化
2021-07-26 vue 组件的 scrollBehavior 2
2021-07-26 vue-router中scrollBehavior的巧妙用法
2021-07-26 页面刷新(vue)
2021-07-26 服务器配置nginx.conf文件
点击右上角即可分享
微信分享提示