안녕하세요 상훈입니다.

1 error and 0 warnings potentially fixable with the `--fix` option.
- npm run serve
- quasar dev

 

노드를 이용하여 프로젝트를 구동 하던 와중에 해당 에러가 발생하였다.

 

중요한건 아니지만 에러 인증 정도.

 

--fix 옵션을 이용하여 뭘 어떻게 하라는건 알겠는데 node를 잘사용해보지 않은 입장에서는 당황스러울 수 있다.

 

에러 해결:

./node_modules/.bin/eslint src --fix

이렇게 하면 된다.

 

그리고 다시 프로젝트 구동!

 

수고용

 

저는 vue.js 를 공부중입니다.

quasar 와 함께용.

 

반응형

안녕하세요 상훈입니다.

Vue.js에서 Javascript의 onclick addEventListener와 같이 onclick 이벤트를 주는 방법을 설명하겠습니다.

뷰는 매우 간단하더군요.

0. 기본문법

<button v-on:click=""></button>
<button @click=""></button>

v-on:click 이 기본, 

그리고 @click이 축약 버전입니다. 입맛에 맞게 사용하시면 됩니다.

1. 익히 알고 있는 함수 호출하기

2. 간단한 연산 결과값 도출

 

1. 함수 호출하기

<button @click="LetsGoVue"></button>

<script>
export default {
  name: 'App',
  data() {},
  methods: {
  	LetsGoVue() {
    	console.log('hello')
    }
  }

</script>

console.log에 출력

 

2. 연산 결과값 도출 [ v-if, v-on:click ] 

예시) 모달창 팝업

버튼 클릭 시, 모달창이 뜨고 사라지게 하는 내용을 구현하겠습니다.

<div class="black-bg" v-if="modalStatus">
    <div class="white-bg">
      <h4>상세페이지</h4>
      <p>상세페이지 내용</p>
      <button class="modal-close" @click="modalStatus = 0 ">닫기</button>
    </div>
</div>

모달레이아웃 div 부분입니다. 

modalStatus라는 변수가 1일 때만 해당 내용이 존재하게 하는 조건문[ v-if ] 으로 구현하였습니다.

button을 클릭시 modalStatus라는 변수에 0을 대입하는 것으로 구현하였습니다.

modalStatus의 기본값

script 내 data 내에 modalStatus 변수의 기본값을 0으로 설정하여 처음 렌더링 되었을 때, 보이지 않게 설정하였습니다.

 

 

 

반응형

안녕하세요 상훈입니다.

Vuejs를 설치하여 사용 할 수 있도록 vue js 설치하는 방법을 간단하게 명령어로 설명하도록 하겠습니다.

$ npm install -g @vue/cli 

이렇게 작성하시면 자동으로 설치가 완료 됩니다.

 

그리고 vue 명령어를 사용하실 수 있게됩니다.

예시) vue 버전 확인하기

$ vue --version

기타 다른명령어가 무엇이 있는지 확인

$ vue 
Usage: vue <command> [options]

Options:
  -V, --version                              output the version number
  -h, --help                                 output usage information

Commands:
  create [options] <app-name>                create a new project powered by vue-cli-service
  add [options] <plugin> [pluginOptions]     install a plugin and invoke its generator in an already created project
  invoke [options] <plugin> [pluginOptions]  invoke the generator of a plugin in an already created project
  inspect [options] [paths...]               inspect the webpack config in a project with vue-cli-service
  serve [options] [entry]                    serve a .js or .vue file in development mode with zero config
  build [options] [entry]                    build a .js or .vue file in production mode with zero config
  ui [options]                               start and open the vue-cli ui
  init [options] <template> <app-name>       generate a project from a remote template (legacy API, requires @vue/cli-init)
  config [options] [value]                   inspect and modify the config
  outdated [options]                         (experimental) check for outdated vue cli service / plugins
  upgrade [options] [plugin-name]            (experimental) upgrade vue cli service / plugins
  migrate [options] [plugin-name]            (experimental) run migrator for an already-installed cli plugin
  info                                       print debugging information about your environment

  Run vue <command> --help for detailed usage of given command.

 

 

이상입니다.

리액트했다가 뷰했다가 환장파티~!

 

https://online.codingapple.com/wp-content/uploads/2021/03/1_oZqGznbYXJfBlvGp5gQlYQ-600x294.jpeg

 

반응형

안녕하세요 상훈입니다.

리액트 - 차트를 이용해 코로나19의 현황을 간단하게 알아보는 예제를 출력하겠습니다.

결과화면

Contents.js

import React, {useState, useEffect} from 'react'
import { Bar, Doughnut, Line } from "react-chartjs-2"
import axios from 'axios'


const Contents = () => {

    const [confirmedData, setConfirmedData] = useState({})
    const [quarantinedData, setQuarantinedData] = useState({})
    const [comparedData, setComparedData] = useState({})




    useEffect(() => {
        const fetchEvents = async () => {
            const res = await axios.get("https://api.covid19api.com/total/dayone/country/kr")
            console.log(res)
            makeData(res.data)

        }
        const makeData = (items)=>{
            const arr = items.reduce((acc, cur) => {
                const currentDate = new Date(cur.Date)
                const year = currentDate.getFullYear()
                const month = currentDate.getMonth()
                const date = currentDate.getDate()
                const confirmed = cur.Confirmed
                const active = cur.Active
                const death = cur.Death
                const recovered = cur.Recovered

                const findItem = acc.find(a=> a.year === year && a.month === month)

                if(!findItem){
                    acc.push({ year, month, date, confirmed, active, death, recovered })
                }
                if(findItem && findItem.date < date){
                    findItem.active = active
                    findItem.death = death
                    findItem.date = date
                    findItem.year = year
                    findItem.month = month
                    findItem.recovered = recovered
                    findItem.confirmed = confirmed

                }
                return acc;

            }, [])


            const labels = arr.map(a => `${a.month+1}월`)
            setConfirmedData({
                labels,
                datasets: [
                    { 
                        label: "국내 누적 확진자", 
                        backgroundColor: "salmon",
                        fill: true,
                        data: arr.map(a => a.confirmed)
                    },
                ]
            })

            setQuarantinedData({
                labels,
                datasets: [
                    { 
                        label: "월별 격리자 현황", 
                        borderColor: "salmon",
                        fill: false,
                        data: arr.map(a => a.active)
                    },
                ]
            })

            const last = arr[arr.length -1 ]
            setComparedData({
                labels: ["확진자","격리해제","사망"],
                datasets: [
                    { 
                        label: "누적 확진, 해제, 사망 비율", 
                        backgroundColor: ["#ff3d67", "#059bff", "#ffc233"],
                        borderColor: ["#ff3d67", "#059bff", "#ffc233"],
                        fill: false,
                        data: [last.confirmed, last.recovered, last.death]
                    },
                ]
            })
        }
        fetchEvents()
    }, [])

    return (
        <section>
            <h2>국내 코로나 현황</h2>
            <div className="contents">
                <div>
                    <Bar data={confirmedData} options={
                        {title: { display : true, text: "누적 확진자 추이", fontSize: 16 } },
                        {legend: {display : true, position: "bottom"} }
                    } />
                </div>
                <div>
                    <Line data={quarantinedData} options={
                        {title: { display : true, text: "월별 격리자 현황", fontSize: 16 } },
                        {legend: {display : true, position: "bottom"} }
                    } />
                </div>
                <div>
                    <Doughnut data={comparedData} options={
                        {title: { display : true, text: `누적 확진, 해제, 사망 (${new Date().getMonth() + 1 })`, fontSize: 16 } },
                        {legend: {display : true, position: "bottom"} }
                    } />
                </div>
            </div>
        </section>
    )
}

export default Contents

 

 

App.css

.App {
  display: flex;
  flex-direction: column;
}

.header {
  background-color: #3b5998;
  display: flex;
  justify-content: space-between;
  padding: 1rem 2rem;
  align-items: center;
}

.header h1{
  color:azure;
}

.header select {
  height: 30px;
  width: 140px;
  border-radius: 5px;
  border: none;
}

section {
  padding: 1rem;
}

.contents {
  width: 60%;
  text-align:center;
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap : 2rem;
}

 

원형차트는 아무래도 확진자 대비 나머지 비율이 너무 작아서 안보이는 건지,,,, 아니면 제가 api 적용을 잘못한건지 헷갈립니다... ㅠㅠ

나중에 확인 해야할 것 같아요. 그럼 이만ㅌㅌ

 

 

강의 참고

React.js로 웹앱 만들기

 

리액트와 가까워지기.
(어렵당)

 

반응형

안녕하세요 상훈입니다.

리액트에서 Axios 요청을 사용하는 방법(chart ... etc)을 알아보도록 하겠습니다.

$ npm install axios react-chartjs-2 --save

터미널에 복사 붙여넣기 해주시면 됩니다.

 

Axios는 js의 Ajax와 유사합니다.

브라우저와 Node.js에서 Promise API를 통신 방식으로서,

 프론트와 백을 연결하여 HTTP 비동기 통신 방식입니다.

 

받아오는 방식은 JSON 입니다.

이 중에 GET 방식을 진행해볼건데, 

axios.get(url)

로 사용이 가능합니다. 

 


예제) 코로나 현황 검색

우리나라의 covid19 현황을 검색해보겠습니다.

저는 Google Extensions : Talend API Tester를 사용했구요, api 통신 테스터 아무거나 사용하셔도 무방합니다.

api 테스트 send 작업 - 우리나라 코로나 현황
결과값

이렇게 JSON 형태로 값이 받아와졌습니다. 

이제 web에 적용을 하도록 하겠습니다.

Contents.js    :  React.js file

import React, {useState, useEffect} from 'react'
import axios from 'axios'


const Contents = () => {

    useEffect(() => {
        const fetchEvents = async () => {
            const res = await axios.get("https://api.covid19api.com/total/dayone/country/kr")
            console.log(res)
        }
        fetchEvents()
    })

    return (
        <section>
            <h2>국내 코로나 현황</h2>
            <div className="contents">
            

            </div>
        </section>
    )
}

export default Contents

 

1. useState와 useEffect를 import 해주셔서 앱이 로딩이 될 때 사용을 하도록 하고,

2. axios를 import하여 axios를 사용할 수 있게 해줍니다.

3. 그리고 async await을 사용하여 바로 스크립트가 실행되는 것이 아닌, 먼저 모든 페이지가 로딩 된 후에 데이터를 찾는 것으로 설정하였습니다.

 

console창 확인

 

이렇게 object 형태로 데이터를 받아왔습니다.

 

반응형

 

리액트 코드를 작성하면서 snippets가 작용할 수 있게.

= h1 만 작성하여도 자동으로 <h1></h1>이 작성되게 하는 익스텐더

 

 

반응형

안녕하세요 상훈입니다.

자바스크립트로 문자열을 나누는 split 함수를 사용하도록 하겠습니다.

<script>
  cosnt yearInput = prompt('태어난 해는?', '')
  const year = Number(yearInput)
  const tags = '원숭이,닭,개,돼지,쥐,소,호랑이,토끼,용,뱀,말,양'.split(',')
  alert(`${year}년에 태어났다면, ${tags[year%12]} 띠 입니다.`)
</script>

결과

 

Split 함수 예제를 알아보았습니다.

반응형

안녕하세요 상훈입니다.

리액트 훅으로 useEffect를 사용하여 웹페이지 접속 3초 후Title 부분이 바뀌는 예제를 작성하도록 하겠습니다.

App.js

import React, {useState, useEffect } from "react";

const useTitle = initialTitle => {
  const [title, setTitle] = useState(initialTitle)
  const updateTitle = () => {
    const htmlTitle = document.querySelector("title")
    htmlTitle.innerText = title
  }
  useEffect(updateTitle, [title])
  return setTitle
}


function App() {
  const titleUpdater = useTitle("Loading...")  // 시작할 때
  setTimeout(()=> titleUpdater("Home"), 3000)  // 3초 후 

  return (
    <div className="App">
      <div>Hi</div>    
    </div>
  );
}

export default App;

Loading... -> 3초후 -> Home 

으로 바뀌는 페이지 제목을 확인하실 수 있습니다.

결과 화면 캡쳐
끝~!!

 

 

강의 참고 : 니콜라스님

 

All Courses – 노마드 코더 Nomad Coders

초급부터 고급까지! 니꼬쌤과 함께 풀스택으로 성장하세요!

nomadcoders.co

 

 

 

반응형

+ Recent posts