首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Vue中用插槽获取数据?

如何在Vue中用插槽获取数据?
EN

Stack Overflow用户
提问于 2021-08-31 13:14:10
回答 2查看 129关注 0票数 1

我有这样的代码块。

代码语言:javascript
复制
<template slot="name" slot-scope="row">{{row.value.first}} {{row.value.last}}</template>

我还有个头球。

代码语言:javascript
复制
    { isActive: true, age: 38, name: { first: 'Jami', last: 'Carney' } },
    { isActive: false, age: 27, name: { first: 'Essie', last: 'Dunlap' } },
    { isActive: true, age: 40, name: { first: 'Thor', last: 'Macdonald' } },  

这段代码运行得很清楚,但我想显示API中的数据。我需要知道哪些条款?我以前用过Axios来做反应。在哪里可以定义Axios方法?我是否需要更改模板槽而不是:v槽?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-08-31 14:12:10

尽管您可以直接从组件代码中进行API调用,但这并不意味着您应该这样做。最好将API调用解耦到一个单独的模块中。下面是一种很好的方法,它正确地遵循关注点分离(SoC)原则:

  1. 如果还没有在src下创建一个目录src
  2. services下,创建名为api.service.js的新文件。

api.service.js

代码语言:javascript
复制
import axios from 'axios';

const baseURL = 'http://localhost:8080/api'; // Change this according to your setup

export default axios.create({
    baseURL,
});
  1. 创建另一个文件peopleData.service.js
代码语言:javascript
复制
import api from './api.service';
import handleError from './errorHandler.service'; // all the error handling code will be in this file, you can replace it with console.log statement for now.

export default {
    fetchPeopleData() {
        return api.get('/people')
            .catch((err) => handleError(err));
    },

    // All other API calls related to your people's (users'/customers'/whatever is appropriate in your case) data should be added here.
    addPerson(data) {
        return api.post('/people', data)
            .catch((err) => handleError(err));
    },
}

现在,您可以将此服务导入组件并调用该函数。

代码语言:javascript
复制
<template>
... Template code
</template>

<script>
import peopleDataService from '@/services/peopleData.service';

export default {
    data() {
        return {
            rows: [],
        };
    },
    mounted() {
        peopleDataService.fetchPeopleData().then((res) => {
            if (res && res.status == 200) {
                this.rows = res.data;
            }
        });
    },
}
</script>

你还没告诉我们你目前的计划。如果您使用的是Vue-路由器,最好在导航保护中获取数据,特别是如果您的组件依赖于数据:数据取取

只需将代码从挂载()转换为导航保护即可。this可能不可用,所以您必须使用next回调来设置rows数组,这在上面的链接中已经解释过了。

票数 0
EN

Stack Overflow用户

发布于 2021-08-31 13:24:04

您可以在方法或挂载中使用Axios。

代码语言:javascript
复制
mounted(){
    this.loading = true;
    axios
    .get(`${this.backendURL}/api/v1/pages/layouts` , authHeader())
    .then(response => (this.layouts = response.data.data))
    .catch(handleAxiosError);
}

methods: {
      /**
        * Search the table data with search input
        */
      uncheckSelectAll(){
        this.selectedAll = false
      },
      onFiltered(filteredItems) {
          // Trigger pagination to update the number of buttons/pages due to filtering
          this.totalRows = filteredItems.length;
          this.currentPage = 1;
      },
      handlePageChange(value) {
          this.currentPage = value;
          axios
          .get(`${this.backendURL}/api/v1/pages?per_page=${this.perPage}&page=${this.currentPage}` , authHeader())
          .then(response => (this.pagesData = convert(response.data.data),
                             this.pagesDataLength = response.data.pagination.total));
        },
      handlePerPageChange(value) {
        this.perPage = value;
        this.currentPage = 1;
        axios
        .get(`${this.backendURL}/api/v1/pages?per_page=${this.perPage}&page=${this.currentPage}` , authHeader())
        .then(response => (this.pagesData = convert(response.data.data),
                           this.pagesDataLength = response.data.pagination.total));
      },
      deletePage(){
        this.loading = true
        this.$bvModal.hide("modal-delete-page");
        window.console.log(this.pageIdentity);
        if (!roleService.hasDeletePermission(this.pageIdentity)){
          return;
        }
        axios
        .delete(`${this.backendURL}/api/v1/pages/${this.page.id}` , authHeader())
        .then(response => (
          this.data = response.data.data.id,
          axios
          .get(`${this.backendURL}/api/v1/pages?per_page=${this.perPage}&page=${this.currentPage}` , authHeader())
          .then(response => (this.pagesData = convert(response.data.data),
                             this.pagesDataLength = 

    response.data.pagination.total)),
              alertBox(`Page deleted succesfully!`, true)
              ))
            .catch(handleAxiosError)
            .finally(() => {
                this.loading =  false
            });
          }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68999360

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档