Ruby后端设置接口
- 选择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
- 如果使用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组件接收和处理数据
- 在Vue组件中使用
axios
:
- 安装
axios
:npm 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>
- 使用
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>