Vue.js 폼 submit

1 개요[ | ]

Vue.js 폼 submit
  • Vue.js에서 ajax를 수행할 수 있는 모듈로 vue-resource, axios가 있음
  • 공식적으로 권장되는 것은 axios
  • jQuery를 사용한다면 그냥 jQuery로 해도 됨

2 예시 1: axios ★★[ | ]

<div id="app">
  <form id="myForm" @submit.prevent="sendPost">
    <input type="text" name="title" v-model="title"><br>
    <textarea name="body" v-model="body"></textarea><br>
    <button>Send</button>
  </form>
</div>

<script src="https://unpkg.com/vue/dist/vue.global.prod.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
  Vue.createApp({
    data() {
      return {
        title: 'hello',
        body: 'world'
      }
    },
    methods: {
      sendPost() {
        axios.post('//jsonplaceholder.typicode.com/posts', {
          userId: 1,
          title: this.title,
          body: this.body
        })
        .then(function(res) {
          console.log(res.data)
        }, function() {
          console.log('failed')
        })
      }
    }
  }).mount('#app')
</script>
→ Send 버튼을 누르면 콘솔창에 다음 내용이 출력된다.
Object {userId: 1, title: "hello", body: "world", id: 101}

3 예시 2: jQuery[ | ]

<div id="app">
  <form id="myForm" @submit.prevent="sendPost">
    <input type="text" name="title" v-model="title"><br>
    <textarea name="body" v-model="body"></textarea><br>
    <button>Send</button>
  </form>
</div>

<script src="https://unpkg.com/vue/dist/vue.global.prod.js"></script>
<script src="https://code.jquery.com/jquery.min.js"></script>
<script>
  Vue.createApp({
    data() {
      return {
        title: 'hello',
        body: 'world'
      }
    },
    methods: {
      sendPost() {
        $.post('//jsonplaceholder.typicode.com/posts', {
          userId: 1,
          title: this.title,
          body: this.body
        })
        .done((data) => {
          console.log(data)
        })
        .fail(() => {
      	  console.log('failed')
        })
      }
    }
  }).mount("#app")
</script>
→ Send 버튼을 누르면 콘솔창에 다음 내용이 출력된다.
Object {userId: 1, title: "hello", body: "world", id: 101}

4 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}