在Nuxt.js如何使用Vuex最新教程

在这里插入图片描述

简介
在项目开发过程中,遇到vuex报错

Classic mode for store/ is deprecated and will be removed in Nuxt 3.

在nuxt官网查了一下发现是不建议使用这种语法 

在 nuxtjs 升级到2.4之后,采用旧的 store 配置方式,配置 vuex 将会报错
nuxt中vuex 老版本写法
import Vue from 'vue'

import Vuex from 'vuex'

import geo from './modules/geo'

import home from './modules/home'

Vue.use(Vuex)

const store = () => new Vuex.Store({
    
    
  modules: {
    
    
    geo,
    home
  },
  actions: {
    
    
    async nuxtServerInit({
    
    
      commit
    }, {
    
    req, app}) {
    
    
      const {
    
    
        status,
        data: {
    
    
          province,
          city
        }
      } = await app.$axios.get('/geo/getPosition')
      commit('geo/setPosition',status===200?{
    
    city,province}:{
    
    city:'',province:''})
      const {
    
    status:status2,data:{
    
    menu}}=await app.$axios.get('geo/menu')
      commit('home/setMenu',status2===200?menu:[])
      const {
    
    status:status3,data:{
    
    result}}=await app.$axios.get('/search/hotPlace',{
    
    
        params:{
    
    
          city:app.store.state.geo.position.city.replace('市','')
        }`在这里插入代码片`
      })
      commit('home/setHotPlace',status3===200?result:[])
    }
  }
})

export default store
新版本用法
Nuxt.js 支持两种使用 store 的方式,你可以择一使用:

普通方式: store/index.js 返回一个 Vuex.Store 实例

模块方式: store 目录下的每个 .js 文件会被转换成为状态树指定命名的子模块 (当然,index 是根模块)
普通方式
使用普通方式的状态树,需要添加 store/index.js 文件,并对外暴露一个 Vuex.Store 实例:

import Vue from 'vue'

import Vuex from 'vuex'

Vue.use(Vuex)

const store = () => new Vuex.Store({
    
    

    state: {
    
    
        count: 0
    },
    mutations: {
    
    
        increment(state) {
    
    
            state.count + 100
        }
    }
})

export default store
普通方式在组件中使用
<template>
    <button @click="$store.commit('increment')">{
   
   { $store.state.count }}</button>
</template>
模块方式
状态树还可以拆分成为模块,store 目录下的每个 .js 文件会被转换成为状态树指定命名的子模块

使用状态树模块化的方式,store/index.js 不需要返回 Vuex.Store 实例,

而应该直接将 state、mutations 和 actions 暴露出来:

export const state = () => ({
    
    
  count: 0
})

export const mutations = {
    
    
  increment (state) {
    
    
    state.count++
  }
}
其他的模块文件也需要采用类似的方式,如 store/todos.js 文件:

export const state = () => ({
    
    
    list: []
})

export const mutations = {
    
    
    add(state, text) {
    
    
        state.list.push({
    
    
            text: text,
            done: false
        })
    },
    remove(state, {
    
     todo }) {
    
    
        state.list.splice(state.list.indexOf(todo), 1)
    },
    toggle(state, todo) {
    
    
        todo.done = !todo.done
    }
}
在页面中使用 如下所示
<template>
  <ul>
    <li v-for="todo in todos">
      <input type="checkbox" :checked="todo.done" @change="toggle(todo)">
      <span :class="{ done: todo.done }">{
    
    {
    
     todo.text }}</span>
    </li>
    <li><input placeholder="What needs to be done?" @keyup.enter="addTodo"></li>
  </ul>
</template>

<script>
import {
    
     mapMutations } from 'vuex'

export default {
    
    
  computed: {
    
    
    todos () {
    
     return this.$store.state.todos.list }
  },
  methods: {
    
    
    addTodo (e) {
    
    
      this.$store.commit('todos/add', e.target.value)
      e.target.value = ''
    },
    ...mapMutations({
    
    
      toggle: 'todos/toggle'
    })
  }
}
</script>

<style>
.done {
    
    
  text-decoration: line-through;
}
</style>
模块方法顶级定义
需要创建一个文件store/state.js并添加以下内容

export default () => ({
    
    

  counter: 0
  
})

并且相应的 mutations 在文件 store/mutations.js 中

export default {
    
    

  increment (state) {
    
    
  
    state.counter++
    
  }
  
}
模块文件
您可以将模块文件分解为单独的文件:state.js,actions.js,mutations.js和getters.js。

如果您使用index.js来维护state,getters,actions和mutations,同时具有单个单独的操作文件,

那么仍然可以正确识别该文件
项目结构
vuex 并不限制你的代码结构。但是,它规定了一些需要遵守的规则:

1、应用层级的状态应该集中到单个 store 对象中。

2、提交 mutation 是更改状态的唯一方法,并且这个过程是同步的。

3、异步逻辑都应该封装到 action 里面。

只要你遵守以上规则,如何组织代码随你便。

如果 store 文件太大,只需将 action、mutation 和 getter 分割到单独的文件。

对于大型应用,我们会希望把 Vuex 相关代码分割到模块中。下面是项目结构示例:

├── index.html
├── main.js
├── api
│   └── ... # 抽取出API请求
├── components
│   ├── App.vue
│   └── ...
└── store
    ├── index.js          # 我们组装模块并导出 store 的地方
    ├── actions.js        # 根级别的 action
    ├── mutations.js      # 根级别的 mutation
    └── modules
        ├── cart.js       # 购物车模块
        └── products.js   # 产品模块

谢谢观看,如有不足,敬请指教

猜你喜欢

转载自blog.csdn.net/handsomezhanghui/article/details/108294069