Vue.js & Flask - 데이터 주고받기 axios(2) button binding

울이·2020년 8월 3일
0
post-thumbnail

Vue에서 생성한 button과 function을 바인딩 해 보도록 하려고 한다

깃허브 소스는 링크로 첨부한다 → 링크

Vue-Flask Data Binding

이전의 글에서 axios로 front와 back을 연동했다.

axios를 가지고 backend와 frontend에서 데이터를 서로 연동을 해 주었는데 이번에는 list 데이터를 받아 출력하고, 출력 해 주는 이벤트를 button에 할당 해 주려고 한다.

backend - route추가

backend/app.py 수정

이전의 파일에서 핑크색으로 된 부분을 추가했다 → 랜덤으로 생성되는 데이터를 출력 해준다.

from flask import Flask, jsonify
from flask_cors import CORS

from my_util.my_logger import my_logger

import os,string

# instantiate the app
app = Flask(__name__)

# enable CORS
CORS(app, resources={r'/*': {'origins': '*'}})

# sanity check route
@app.route('/', methods=['GET'])
def test_router():
    my_logger.info("hello this is root url!")
    return jsonify('This is Docker Test developments Server!')

@app.route('/health_check', methods=['GET'])
def health_check():
    my_logger.info("health check route url!")
    return jsonify('good')

@app.route('/main_btn',methods=['GET'])
def main_btn():
    my_logger.info("click Main Btn")
    data = []
    string_pool = string.ascii_lowercase
    result_dict={}

    for i in range(15):
        result_val=''

        for i in range(10):
            import random
            result_val += random.choice(string_pool)

        result_dict['key'] = result_val

        data.append(result_dict)

    return jsonify(data)

if __name__ == '__main__':
    app.run(host='0.0.0.0',port=os.getenv('FLASK_RUN_PORT'),debug=os.getenv('FLASK_DEBUG'))

frontend - Dashboard.vue수정

frontend/src/views/Dashboard.vue - html 업데이트

  • 어느 곳 이던지 상관이 없다. 나는 이전의 버튼과 연동할 것이기 떄문에 버튼 바로 밑에 추가 해 주었다
<div class="col-md-12">
    <h1>My Test</h1>
    <button type="button" class="btn btn-success btn-sm">{{my_data}}</button>
    <hr>
    **<ul>
        <li v-for="(msg,index) in ran_str" :key="index">
            {{ msg.key }}
        </li>
    </ul>**
</div>
  • v-for으로 list에 데이터를 추가 해 준다

frontend/src/views/Dashboard.vue - javascript 업데이트

  • export default에 추가 해 주었다
...

data() {
    return {
        ...
        ran_str: [],
				...
		},
},
...
methods:{
	...
	getRanStr(){
	      let path = "http://" + window.location.hostname + ":5000/main_btn";
	      axios.get(path).then((res) => {
	          this.ran_str = res.data;
	          console.log(res.data);
	      }).catch((error) => {
	          console.error(error);
	      });
	
	  },
	...
},
...
  • 페이지가 로딩되며 바로 실행 할 것이 아니기 때문에 created에 추가 해 주지 않았다.

이제 다시 button으로 돌아가서 getRanStr() 함수를 할당 해 주려고 한다.

<button type="button" class="btn btn-success btn-sm" v-on:click="getRanStr">{{my_data}}</button>
  • v-on:click 으로 함수 할당을 해준다

run!!

$ docker-compose up --build

위의 버튼을 누르면 생성이 된다

회고

profile
개발을 개발개발

0개의 댓글