如何使用来自 Laravel API 的项目填充此 Vue select?

How can I populate this Vue select with items coming from a Laravel API?

我正在制作一个由 Laravel 8 APIVue 3 前台组成的注册表-结束。

我在 AuthController 中有这段代码来注册新用户:

class AuthController extends Controller
{

    public function register(Request $request) {

     $rules = [
        'first_name' => 'required|string',
        'last_name' => 'required|string',
        'email' => 'required|email|unique:users,email',
        'password' => 'required|string|confirmed',
        'country' => 'required|string',
        'accept' => 'accepted',
    ]; 

    $fields = $request->validate($rules);

    $user = User::create([
        'first_name' => $fields['first_name'],
        'last_name' => $fields['last_name'],
        'email' => $fields['email'],
        'password' => bcrypt($fields['password']),
        'country' => $fields['country']
    ]);

    $token = $user->createToken('secret-token')->plainTextToken;

    $response = [
        'user' => $user,
        'token' => $token
    ];

    return response($response, 201);
    }
}

在前端,我有:

const registrationForm = {
  data() {
    return {
      apiUrl: 'http://myapp.test/api',
      formSubmitted: false,
      countries: [],
      fields: {
        first_name: '',
        last_name: '',
        email: '',
        password: '',
        country: '',
      },
      errors: {},
    };
  },
  methods: {
    // get Countries
    async getCountries(){
      try {
        const response = await axios
          .get(`${this.apiUrl}/register`)
          .catch((error) => {
            console.log(error);
          });

        // Populate countries array
        this.countries = response.data;

      } catch (error) {
        console.log(error);
      }
    },

    registerUser(){
      // Do Registrarion
      axios.post(`${this.apiUrl}/register`, this.fields).then(() =>{
        // Show success message
        this.formSubmitted = true;

        // Clear the fields
        this.fields = {}

      }).catch((error) =>{
        if (error.response.status == 422) {
          this.errors = error.response.data.errors;
        }
      });
    }
  },
  async created() {
    await this.getCountries();
  }
};

Vue.createApp(registrationForm).mount("#myForm");

objective

为了用国家/地区下拉列表替换“国家/地区”表单字段,我在 register() 方法上方添加了此内容:

public $countries;

public function countries()
{
  return Country::all('id', name', 'code');
}

此外,$rules 数组上方的这一行:

$this->countries = $this->countries();

问题

这是一个 API,我没有意见,所以我 不能 做一些事情:

return view('regisrer-view', compact('countries'));

<select class="form-select">
  @foreach ($countries as $country)
      <option value="{{$country->id}}">{{$country->name}}</option>
  @endforeach
</select>

相反,我需要 API 中的国家/地区列表 ,因此我可以以 Vue 形式输出,如下所示:

<select class="form-control">
    <option value="">Select your country</option>
    <option v-for="country in countries" :value="country.id">{{ country.name }}</option>
</select>

问题

如何使用国家(列表)填充上面的 Vue select?

更新

我在后端做了这个:

public function countries()
{
    return Country::all('id', 'name', 'code');
}

$response = [
    'countries' => $this->countries(),
    'user' => $user,
     'token' => $token
];

正面:

async getCountries(){
  try {
    const response = await axios
      .get(`${this.apiUrl}/register`)
      .catch((error) => {
        console.log(error);
      });

    // Populate countries array
    this.countries = response.data.countries;

    console.log(this.countries);

  } catch (error) {
    console.log(error);
  }
}

当我获取 register 路由时,我在 Chrome 的控制台中收到 422 (Unprocessable Content) 错误。

为什么?

您可以在响应数组中添加类似 'countries' 的参数并分配变量值。您将在 async getCountries() 中得到它作为响应。

$response = [
    'user' => $user,
    'token' => $token,
    'countries' => $this->countries
];

 const response = await axios
      .get(`${this.apiUrl}/register`)
      .catch((error) => {
        console.log(error);
      });

    // Populate countries array
    this.countries = response.data.countries;

为了更好地理解API响应,我建议你应该使用邮递员。

Postman Download