使用 Vuex 和特定于组件的数据构建 Vue [英] Vue structuring with Vuex and component-specific data

查看:16
本文介绍了使用 Vuex 和特定于组件的数据构建 Vue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到很多 Vue.js 项目使用这种结构:

I see a lot of Vue.js projects using this structure:

├── main.js
├── api
│   └── index.js
│   └── services           #containing files with api-calls
│       ├── global.js
│       ├── cart.js
│       └── messages.js
├── components
│   ├── Home.vue
│   ├── Cart.vue
│   ├── Messages.vue
│   └── ...
└── store
    ├── store.js
    ├── actions.js  #actions to update vuex stores
    ├── types.js
    └── modules
        ├── global.js
        ├── cart.js
        └── ...

(具有此结构的示例是Jackblog".)

(An example with this structure is 'Jackblog'.)

因此,例如 Cart.vue 想要更新 Vuex 中的 inCart 数据.为此,购物车导入 actions.js:

So, for example, Cart.vue wants to update the inCart data in Vuex. To do that, the Cart imports actions.js:

import { inCart } from '../../store/actions'

actions.js 导入 api 的 index.js 以便它可以连接到 api.然后它更新 Vuex 存储中的值.

The actions.js imports the api's index.js so it can connect to the api. And then it updates the values in the Vuex store.

好的,这对我来说很清楚.但是现在,我想在 Messages.vue 模块上工作.该模块也应该连接到 api 以获取所有消息,但不必将结果存储在 Vuex 中.唯一需要数据的组件是 Messages.vue 本身,所以它应该只存储在组件的 data() 中.

Ok, so that is clear for me. But now, I want to work on the Messages.vue module. This module should connect to the api as well to get all the messages, but it is not necessary to store the results in Vuex. The only component that needs the data is Messages.vue itself, so it should be stored in the component's data() only.

问题:我无法在 Messages.vue 中导入 actions.js,因为该操作不应更新 Vuex.但我无法将 actions.js 移动到 api 目录,因为这破坏了将所有添加数据的文件放入 store 目录中的逻辑.除此之外,逻辑应该放在 Messages.vue 中.例如,当 api 返回错误时,应设置本地 error-constant.所以它不能由单独的文件处理.

Question: I can't import actions.js inside Messages.vue because the action shouldn't update Vuex. But I can't move the actions.js to the api directory, because that breaks the logic of putting all files that add data to the store in the store-directory. Besides that, the logic should be placed inside Messages.vue. For example when the api returns an error, a local error-constant should be set. So it cannot be handled by a separate file.

进行 api 调用并将它们存储在 vuex 或本地 data() 中的推荐应用程序结构是什么?在哪里放置操作文件、api 文件等?在查看 Jackblog 示例时,它仅支持 Vuex 数据.如何重组它以支持两者?

What is the recommended application structure for making api calls and store them in vuex or local data()? Where to place the actions file, the api files, and so on? When looking to the Jackblog example it supports Vuex data only. How to restructure this to support both?

推荐答案

我正在使用 axios作为进行 API 调用的 HTTP 客户端,我在 src 文件夹中创建了一个 gateways 文件夹,并且每个后端都有文件,创建 axios 实例,如下图

I am using axios as HTTP client for making API calls, I have created a gateways folder in my src folder and I have files for each backend, creating axios instances, like following

myApi.js

import axios from 'axios'
export default axios.create({
  baseURL: 'http://localhost:3000/api/v1',
  timeout: 5000,
  headers: {
    'X-Auth-Token': 'f2b6637ddf355a476918940289c0be016a4fe99e3b69c83d',
    'Content-Type': 'application/json'
  }
})

这些相同的实例用于组件和 vuex 操作中以获取数据,以下是两种方式的详细信息.

These same instances are used in both component and vuex actions to get the data, following are details of both ways.

如果数据只在组件中使用,比如你的 Messages.vue 案例,你可以有一个方法从 api 中获取数据,如下所示:

If the data is being used only in the component, like your case of Messages.vue, you can have a method which will fetch data from the api like following:

export default {
  name: 'myComponent',
  data: () => ({
    contents: '',
    product: []
  }),
  props: ['abc'],
  methods: {
    getProducts (prodId) {
       myApi.get('products?id=' + prodId).then(response => this.product = response.data)
       },
       error => {
          console.log('Inside error, fetching products failed')
          //set error variable here
       })
    }
    ..... 

填充 Vuex 数据

如果您在专用的 vuex 模块中维护产品相关数据,您可以从组件中的方法中分派一个操作,该操作将在内部调用后端 API 并在商店中填充数据,代码如下所示:

Populating Vuex data

If you are maintaining product related data in a dedicate vuex module, you can dispatch an action from the method in component, which will internally call the backend API and populate data in the store, code will look something like following:

组件中的代码:

methods: {
 getProducts (prodId) {
     this.$store.dispatch('FETCH_PRODUCTS', prodId)
  }
}

vuex store 中的代码:

Code in vuex store:

import myApi from '../../gateways/my-api'
const state = {
  products: []
}

const actions = {
  FETCH_PRODUCTS: (state, prodId) => {
    myApi.get('products?id=' + prodId).then(response => state.commit('SET_PRODUCTS', response))
  }
} 

// mutations
const mutations = {
  SET_PRODUCTS: (state, data) => {
    state.products = Object.assign({}, response.data)
  }
}

const getters = {
}

export default {
  state,
  mutations,
  actions,
  getters
}

这篇关于使用 Vuex 和特定于组件的数据构建 Vue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆