Vue3 axios方式发送数据和获取数据

90 阅读1分钟

示例:

<template>
  <div>
    <input ref="title" type="text" placeholder="">
    <input ref="content" type="text" placeholder="">
    <button @click="getValue">获取输入值</button>

  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';

// 创建ref对象和dom绑定
const title = ref(null);
const content = ref(null);

/*生命周期:组件加载*/
onMounted(() => {
  console.log('组件已挂载');
  axios.get("/api/user/list")
    .then(function (response) {
      console.log(response.data);
    })
    .catch(function (error) {
      console.log(error);
    });
});


function getValue() {
  /* title的值不可以在还没赋值的时候获取*/
  const data = {
    title: title.value.value,
    content: content.value.value
  }
  /*执行插入操作*/
  axios.post("/api/user/insert", data)
    .then(function (response) {
      console.log(response.data);
    })
    .catch(function (error) {
      console.log(error);
    });
}
</script>

注意:ref绑定dom的方式很重要。