MST

星途 面试题库

面试题:Ruby与Vue.js集成时数据传递问题

假设你要将Ruby后端与Vue.js前端集成,在Vue组件中通过API调用Ruby后端获取数据并展示。请描述如何在Ruby后端设置接口以正确返回数据给Vue组件,以及在Vue组件中如何正确接收和处理这些数据。
11.2万 热度难度
编程语言Ruby

知识考点

AI 面试

面试题答案

一键面试

Ruby后端设置接口

  1. 选择Web框架:通常Ruby使用Ruby on Rails或Sinatra框架来构建后端接口。以Sinatra为例:
    • 安装Sinatra:在Gemfile中添加gem 'sinatra',然后运行bundle install
    • 创建Sinatra应用:
require'sinatra'

get '/api/data' do
  # 这里获取数据,比如从数据库中获取
  data = { key: 'value' }
  # 将数据以JSON格式返回
  content_type :json
  data.to_json
end
  1. 如果使用Ruby on Rails
    • 创建控制器:运行rails generate controller ApiController
    • 在控制器中定义方法:
class ApiController < ApplicationController
  def data
    data = { key: 'value' }
    render json: data
  end
end
  • 配置路由:在config/routes.rb中添加get '/api/data', to: 'api#data'

Vue组件接收和处理数据

  1. 在Vue组件中使用axios
    • 安装axiosnpm install axios
    • 在Vue组件中:
<template>
  <div>
    <div v-if="data">
      <p>{{ data.key }}</p>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      data: null
    };
  },
  mounted() {
    axios.get('/api/data')
    .then(response => {
        this.data = response.data;
      })
    .catch(error => {
        console.error('Error fetching data:', error);
      });
  }
};
</script>
  1. 使用fetch API(不依赖第三方库)
<template>
  <div>
    <div v-if="data">
      <p>{{ data.key }}</p>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      data: null
    };
  },
  mounted() {
    fetch('/api/data')
    .then(response => response.json())
    .then(data => {
        this.data = data;
      })
    .catch(error => {
        console.error('Error fetching data:', error);
      });
  }
};
</script>