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

查看:179
本文介绍了使用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目录,因为这破坏了将所有添加数据的文件放入存储目录的逻辑.除此之外,逻辑应该放在Messages.vue内部.例如,当api返回错误时,应设置本地error-常数.因此它不能由单独的文件处理.

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文件夹,并且每个后端都有文件,从而创建了

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'
  }
})

component和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存储中的代码:

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天全站免登陆