1. vue create real-project

하고나면 npm 사용할건지 yarn 사용할건지 물어봄

2. cd real-project 

3. npm run serve

#npm 사용 포트 설정해줄 때 npm run serve -- --port 포트번호

#ctrl+C 하면 종료

4. tailwind 설정

  [tailwind CSS 패키지 설치]

  $ npm install tailwindcss --save-dev

  [/tailwind.config.js 생성]
  $ node_modules/.bin/tailwind init tailwind.config.js

  [/.postcssrc.js 생성 및 설정코드 작성]
  $ vi .postcssrc.js

module.exports = {
	"plugins": [
    	require)'postcss-import')(),
        require('tailwindcss')('./tailwind-config.js'),
        require('autoprefixer')(),
    ]
}

 [/src/assets/styles/main.css 파일 생성 및 tailwind 설정]

@tailwind preflight;
@tailwind utilities;

 [/src/App.vue 파일 수정]

 *App.vue 파일에 import '@/assets/styles/main.css' 추가

 <script>안에다가 

 $ import '@/assets/styles/main.css' //추가

[main.js에 내용추가]

$tailwindcss/tailwind.css'

 

#script 내에 Import해두고 사용하지 않으면 오류뜸 → 지워줘야 함

 

두번째로 tailwind 설정한 방법

1. ./src/assets/tailwind.css 만들고 추가

/* tailwind사용하기 위해 */
@tailwind base;
@tailwind components;
@tailwind utilities;

 

2. root에 postcss.config.js 만들고 아래코드 입력

const autoprefixer = require('autoprefixer')
const tailwindcss = require('tailwindcss')

module.exports = {
    plugins : [autoprefixer, tailwindcss]
}

3. root에 vue.config.js 있으면 거기다 없으면 만들어서 추가

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true
},
{
  configureWebpack:{
    module:{
      rules:[
      {
        test: /\.css$/,
        use: ['postcss-loader']
      }
    ]
  }}
})

4. 용량문제 발생할 때 대비해서 purgecss 설치해주기 ★ (불필요한 클래스나 css 삭제해줌)

$ npm add —dev @fullhuman/postcss-purgecss 

yarn쓰면 yarn으로 설치

postcss.config.js에 내용추가

const autoprefixer = require('autoprefixer')
const tailwindcss = require('tailwindcss')  
//아래 내용 추가
const purgecss = postcssPurgecss({
    content: ['./public/**/*.html', './src/**/*.vue', './src/**/*.js'],
    defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || [],
    whitelistPatterns: [
     /-(leave|enter|appear)(|-(to|from|active))$/,
     /^(?!(|.*?:)cursor-move).-move$/,
     /^router-link(|-exact)-active$/
   ]
  })

module.exports = {
    plugins : [autoprefixer, 
        tailwindcss,
        process.env.NODE_ENV !== 'development'?purgecss:''                ←
    ]
}

참고자료 : https://imkh.dev/vue-tailwindcss/

'개발 > 졸작' 카테고리의 다른 글

npm-gyp 에러  (0) 2023.02.14
가상환경없이 OnlineJudge 커스터마이징  (0) 2023.02.09
참고자료  (0) 2023.02.06
自己開發  (0) 2023.01.25
JS-console  (0) 2023.01.25

[tailwind]

https://cron-tab.github.io/2018/03/16/js-react/js-react-tailwind/

 

리엑트/뷰 프로젝트에서 테일윈드 CSS 적용하기 (React/Vue + Tailwind CSS)

UI 프레임워크 몇 가지를 써봤는데 결국 커스텀하는 부분에서 어려움을 많이 겪었습니다.그러던 가운데 Tailwind CSS를 알게 되어 써보니 미리 정의되어 있는 클래스 이름만 사용하면 되기 때문에

cron-tab.github.io

 

[vue]

https://ux.stories.pe.kr/119

 

Vue.js의 이벤트 사용 방법 정리

Vue.js에서 이벤트를 다루는 방법에 대해서 간단히 정리하려고 합니다. HTML에는 나 처럼 당연히 알고 있는 기본 이벤트가 있습니다. 그리고 이미 javascript를 통해서 기본 이벤트와 어우러지게 사용

ux.stories.pe.kr

https://webisfree.com/2019-01-17/vuejs%EC%97%90%EC%84%9C-settimeout-%EC%82%AC%EC%9A%A9%ED%95%98%EB%8A%94-%EB%B0%A9%EB%B2%95-%ED%83%80%EC%9D%B4%EB%A8%B8-%EB%A7%8C%EB%93%A4%EA%B8%B0

 

VueJS에서 setTimeout 사용하는 방법, 타이머 만들기

VueJS에서 setTimeout() 타이머 함수를 만드는 방법을 알아봅니다. 어떻게하면 될까요?

webisfree.com

 

[서버 연동]

https://vlee.kr/4155

 

vue.js - express로 frontend, backend 연동하기 예제 - Vlee's Tale

작업 디렉토리 생성 $ mkdir example 프론트엔드와 백엔드 작업을 하게 될 작업디렉토리를 생성한다. Frontend 작업디렉토리 생성 및 front 서버 실행 $ npm install -g yarn $ npm install -g @vue/cli $ vue create fronten

vlee.kr

https://leeceo97.tistory.com/54

 

프로젝트(1)프론트, 백엔드 통신 방법(feat.django, react)

새롭게 프로젝트를 시작하며 개발전 1주일간 3파트로 프로젝트 사전 준비를 하였다. (1) 프론트, 백엔드 통신방법 (2) 기술스택 선정, 협업 노하우 (3) token, django user, 소셜로그인 위의 3가지를 사전

leeceo97.tistory.com

 

[github]

https://tagilog.tistory.com/377

 

[GITHUB 사용법] 왕초보를 위한 깃허브사용법 (Git사용법)

코딩할 때 뺄래야 뺄 수 없는 서비스 중 하나가 GitHub (깃허브) 입니다. 현역 프로그래머에게는 너무나 친숙한 서비스지만, 코딩 초보자에게는 생소할 수도 있습니다. 그래서 이번에는 코딩 초보

tagilog.tistory.com

[react]

ckeditor : https://jjong-factory.tistory.com/55

 

CKEditor5 - Web Editor CKEditor5 이미지 업로드

시작에 앞서 일단 CKEditor 를 사용하기로 마음을 먹었는데, 에디터를 커스텀 할 때 가장 첫 번째로 문제가 되는 점은 역시 이미지를 업로드 하는 문제일 것이다. CKEditor는 해당 부분을 굉장히 말끔

jjong-factory.tistory.com

게시판 : https://falaner.tistory.com/58

 

[react] 간단한 리액트 게시판 만들기 : WYSIWYG ckeditor - ① 인터페이스

간단한 입출력 기능을 가진 리액트 게시판을 하나 만들어보는 예제를 해보려고 한다. 나중에 소스코드도 올려둘테니 필요한 분들은 받아서 한번 살펴보길 바란다. 완성된 프로젝트 소스코드 git

falaner.tistory.com

 

'개발 > 졸작' 카테고리의 다른 글

npm-gyp 에러  (0) 2023.02.14
가상환경없이 OnlineJudge 커스터마이징  (0) 2023.02.09
real-project 과정  (0) 2023.02.06
自己開發  (0) 2023.01.25
JS-console  (0) 2023.01.25

😀실행시킬 때

옵션 - 터미널에서 새터미널 열고 

$ npm run serve

위 주소에 접속하면
입력한 hihihihihi 가 출력됨

=>코드를 수정할 때마다 실시간으로 반영된다.

 

public : html 파일, 기타파일 보관 

src : 수정하는 소스코드들 있는 곳 

 

#메뉴바 및 스타일 

// template안에 HTML 짜고

// script 안에 JS 짜고

// style 안에는 CSS 짜고

<template>

 

  <div class="menu">

    <a>Home</a>

    <a>Products</a>

    <a>About</a>

  </div>

 

  <img alt="Vue logo" src="./assets/logo.png">

  <div>

    {{ logo }}

    <h4 class="bang" :style="스타일">{{products[0]}}</h4>

    <p>{{ price1 }}만원</p> <!--//밑에 있는 데이터 넣어준거임 -->

  </div>

  <div>

      <h4  class="bang" :style="스타일">{{products[1]}}</h4>

      <p>{{price2}}만원</p>

  </div>

  <div>

      <h4 class="bang" :style="스타일">{{products[2]}}</h4>

      <p>{{price2}}만원</p>

  </div>

  <HelloWorld msg="Welcome to Your Vue.js App"/>

</template>

 

<script>

import HelloWorld from './components/HelloWorld.vue'

 

export default {

  name: 'App',

  data(){

    return {  // 안에 데이터, 변수 보관

      price1 : 60,

      price2 : 40,

      logo : '원룸샵',

      스타일 : 'color : purple',  //스타일은 이런식으로

      products : ['역삼동원룸', '천호동원룸', '마포구원룸'],

    }

  },

  components: {

    HelloWorld

  }

}

</script>

 

<style>

#app {

  font-family: Avenir, Helvetica, Arial, sans-serif;

  -webkit-font-smoothing: antialiased;

  -moz-osx-font-smoothing: grayscale;

  text-align: center;

  color: #2c3e50;

  margin-top: 60px;

}

 

.menu{

  background : darkslateblue;

  padding:15px;

  border-radius: 5px;

}

.menu a{

  color : white;

  padding: 10px;

}

</style>

 

 

 

#반복문 

반복문은 v-for = "작명 in 3" <- 3번 반복한다

반복문 쓸 때는 key(유니크한 문자나 숫자 기입) 써주지 않으면 에러남 

이모티콘 표기한 부분 중심으로 보면됨

<div class="menu">

<!-- i 변수 통해서 0~i 숫자 출력도 가능 -->
<!-- <a v - for = "작명 in 3" :key="작명">Home</a> -->
<a v-for = "a in 메뉴들" :key="a">{{ a }}</a>🐶
</div>
 
<script>
import HelloWorld from './components/HelloWorld.vue'

export default {
name: 'App',
data(){
return { //이 안에 데이터, 변수 보관
메뉴들 : ['Home', 'Shop', 'About'],🐶
price1 : 60,
price2 : 40,
logo : '원룸샵',
스타일 : 'color : purple', //스타일은 이런식으로
products : ['역삼동원룸', '천호동원룸', '마포구원룸'],
}
},
components: {
HelloWorld
}
}
</script>
 둘다 같은말  
 <div v-for="(a,i) in 3" :key="i">
 <div v-for="(a,i) in products" :key="i">
 스타일 제외하고 같은 말
 <h4 class="bang" :style="스타일">{{products[i]}}</h4>
 <h4>{{ a }}</h4>

 

#event handler 함수(기본적으로 함수명은 영어로 쓰는것이 오류가 안남

전통적인 js에서는 onClick 으로 사용 → vue에서는 v-on:click 이나 @click으로 사용

@click으로 버튼 누르면 이벤트 발생하게끔 해주고 버튼을 누르면 변하는 데이터에 데이터바인딩을 해줌 

►데이터 바인딩 {{  여기 }} script에서 만든 데이터를 넣어줌 

@click="신고수++" 로 신고수를 하나씩 증가시키겠다 = @click="신고수 += 1" = @click="신고수 = 신고수 + 1"

@mouseover 는 마우스 가까이 댈때마다 이벤트 발생하게끔  이 외에도 여러가지 이벤트핸들러가 있음 

# 입력할 코드가 길 경우에는 <script>에 함수를 만들어서 사용할 수도 있음 

//둘 다 같은 말 함수사용했냐 아니냐 차이 
<button @click="신고수++">허위매물신고</button> <span>신고수 : {{ 신고수 }}</span>
<button @click="increase()">허위매물신고</button> <span>신고수 : {{ 신고수 }}</span>

script안에 생성한 increase 함수

#모달창(UI/UX)★

이미지나 글씨 클릭하면 뜨는 창

UI 생성 

1. template내 빈박스 두개 생성 후 

2. 데이터에 따라 UI가 어떻게 보일지 작성 

팝업창 구현
<script> 데이터안에 팝업창 현재상태 저장
이런식으로 원하는 글씨 안에 모달창 관련 Onclick을 해줌
UI/UX 스타일 구현

[닫기버튼]

여기서 false는 == 해주면 동작하지 않음

&&닫기버튼까지 한 코드/화면 

// template안에 HTML 짜고 
// script 안에 JS 짜고 
// style 안에는 CSS 짜고 
<template>

  <div class="black-bg" v-if="모달창열렸나 == true">  
    <div class="white-bg">
      <h4>상세페이지</h4>
      <p>상세내용</p>
      <button @click="모달창열렸나 = false"> 닫기 </button>
    </div>
  </div>

  <div class="menu">
    <a v-for = "a in 메뉴들" :key="a">{{ a }}</a> 
  </div>

  <div>
    <img src="./assets/room0.jpg" class="room-img">
    <h4 @click="모달창열렸나 = true">{{products[0]}}</h4>
    <p>50만원</p> <!--//밑에 있는 데이터 넣어준거임 -->
    <!-- <button @click="신고수++">허위매물신고</button> <span>신고수 : {{ 신고수 }}</span> -->
    <button @click="신고수[0]++">허위매물신고</button> 
    <span>신고수 : {{ 신고수[0] }}</span>
  </div>
  <div>
    <img src="./assets/room1.jpg" class="room-img">
      <h4>{{products[1]}}</h4>
      <p>60만원</p>
    <button @click="신고수[1]++">허위매물신고</button> 
    <span>신고수 : {{ 신고수[1] }}</span>
  </div>
  <div>
    <img src="./assets/room2.jpg" class="room-img">
      <h4>{{products[2]}}</h4>
      <p>100만원</p>
    <button @click="신고수[2]++">허위매물신고</button> 
    <span>신고수 : {{ 신고수[2] }}</span>
  </div>
  <HelloWorld msg="Welcome to Your Vue.js App"/>
</template>

<script>

import data from './assets/oneroom.js';  //import 해줌 
import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'App',
  data(){
    return {  //이 안에 데이터, 변수 보관
      원룸들 : data,  //import 해준 데이터 사용 
      모달창열렸나 : false, //모달창의 현재 상태 저장
      신고수 : [0, 0, 0],
      메뉴들 : ['Home', 'Shop', 'About'],
      products : ['역삼동원룸', '천호동원룸', '마포구원룸'],
    }
  },
  methods : {
    // 여기 안에다가 함수 만들어 넣으면 됨
    increase(){
      this.신고수 += 1;
    }
  },
  components: {
    HelloWorld
  }
}
</script>

<style>
body{
  margin : 0
}
div {
  box-sizing: border-box;
}
.black-bg{
  width: 100%; height:100%;
  background: rgba(0,0,0,0.5);
  position: fixed; padding: 20px;
}
.white-bg{
  width: 100%; background: white;
  border-radius:8px;
  padding:20px;
}
.room-img{
  width: 100%;
  margin-top:40px;
}
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}

.menu{
  background : darkslateblue;
  padding:15px;
  border-radius: 5px;
}
.menu a{
  color : white;
  padding: 10px;
}
</style>

화면에 세개의 img가 뜨고 그 밑에 허위매물신고 버튼을 누르면 하나씩 증가하는 것 확인해볼 수 있음
설정해뒀던 제목 입력하면 팝업창이 뜨고 닫기 버튼을 누르면 팝업창이 닫힘


[내용불러오기] import / export 

긴 내용을 vue에다가 직접 적기에는 가독성이 떨어지므로 다른 파일에 작성해서 불러오는 식으로 한다

import방법 import 변수명 from 해당파일경로

위에 했던 내용들 import 통해서 구현도 가능 

✖︎ import 해줄 때 변수명은 export 할 때의 형식과 똑같이 써야함

<template>

  <div class="black-bg" v-if="모달창열렸나 == true">  
    <div class="white-bg">
      <h4>상세페이지</h4>
      <p>상세내용</p>
      <button @click="모달창열렸나 = false"> 닫기 </button>
    </div>
  </div>

  <div class="menu">
    <a v-for = "a in 메뉴들" :key="a">{{ a }}</a> 
  </div>

  <div>
    <!-- <img src="./assets/room0.jpg" class="room-img"> -->
    <img :src="원룸들[0].image" class="room-img"> <!--속성 데이터바인딩 해줄때는 : 꼭 해줘야함-->
    <h4>{{ 원룸들[0].title }}</h4>  
    <p>{{ 원룸들[0].price }}원</p>
  </div>
  <div>
    <img :src="원룸들[1].image" class="room-img"> 
    <h4>{{ 원룸들[1].title }}</h4>  
    <p>{{ 원룸들[1].price }}원</p>
  </div>
  <div>
    <img :src="원룸들[2].image" class="room-img"> 
    <h4>{{ 원룸들[2].title }}</h4>  
    <p>{{ 원룸들[2].price }}원</p>
  </div>
  <HelloWorld msg="Welcome to Your Vue.js App"/>
</template>

✖︎ import할 데이터들 사용할 때 script에 저장한 데이터명.자료내 표시하고싶은 부분 

✖︎ 원룸들[1], [2] 에서 옆에 [1] 표기한건 export한 데이터 중 표시하고자 하는 내용의 아이디임

<script>

import data from './assets/oneroom.js';  //import 해줌 
import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'App',
  data(){
    return {  //이 안에 데이터, 변수 보관
      원룸들 : data,  //import 해준 데이터 사용 
      모달창열렸나 : false, //모달창의 현재 상태 저장
      신고수 : [0, 0, 0],
      메뉴들 : ['Home', 'Shop', 'About'],
      products : ['역삼동원룸', '천호동원룸', '마포구원룸'],
    }
  },
  methods : {
    // 여기 안에다가 함수 만들어 넣으면 됨
    increase(){
      this.신고수 += 1;
    }
  },
  components: {
    HelloWorld
  }
}
</script>

✖︎ import해준 데이터는 data 안에 저장해서 html에서 사용가능 

 

#조건문 

v-if로 사용함 

조건문 내에서 조건을 입력할 때는 == 을 사용해주고 

이벤트핸들러를 사용할 때는 "= false" "= true " 형식으로 사용해줌 

 

 

 

[완성 전체 코드]

// template안에 HTML 짜고 
// script 안에 JS 짜고 
// style 안에는 CSS 짜고 
<template>

  <div class="black-bg" v-if="모달창열렸나 == true">  
    <div class="white-bg">
      <h4>상세페이지</h4>
      <p>상세내용</p>
      <button @click="모달창열렸나 = false"> 닫기 </button>
    </div>
  </div>

  <div class="menu">
    <a v-for = "a in 메뉴들" :key="a">{{ a }}</a> 
  </div>

  <div>
    <!-- <img src="./assets/room0.jpg" class="room-img"> -->
    <img :src="원룸들[0].image" class="room-img"> <!--속성 데이터바인딩 해줄때는 : 꼭 해줘야함-->
    <h4>{{ 원룸들[0].title }}</h4>  
    <p>{{ 원룸들[0].price }}원</p>
  </div>
  <div>
    <img :src="원룸들[1].image" class="room-img"> 
    <h4>{{ 원룸들[1].title }}</h4>  
    <p>{{ 원룸들[1].price }}원</p>
  </div>
  <div>
    <img :src="원룸들[2].image" class="room-img"> 
    <h4>{{ 원룸들[2].title }}</h4>  
    <p>{{ 원룸들[2].price }}원</p>
  </div>
  <HelloWorld msg="Welcome to Your Vue.js App"/>
</template>

<script>

import data from './assets/oneroom.js';  //import 해줌 
import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'App',
  data(){
    return {  //이 안에 데이터, 변수 보관
      원룸들 : data,  //import 해준 데이터 사용 
      모달창열렸나 : false, //모달창의 현재 상태 저장
      신고수 : [0, 0, 0],
      메뉴들 : ['Home', 'Shop', 'About'],
      products : ['역삼동원룸', '천호동원룸', '마포구원룸'],
    }
  },
  methods : {
    // 여기 안에다가 함수 만들어 넣으면 됨
    increase(){
      this.신고수 += 1;
    }
  },
  components: {
    HelloWorld
  }
}
</script>

<style>
body{
  margin : 0
}
div {
  box-sizing: border-box;
}
.black-bg{
  width: 100%; height:100%;
  background: rgba(0,0,0,0.5);
  position: fixed; padding: 20px;
}
.white-bg{
  width: 100%; background: white;
  border-radius:8px;
  padding:20px;
}
.room-img{
  width: 100%;
  margin-top:40px;
}
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}

.menu{
  background : darkslateblue;
  padding:15px;
  border-radius: 5px;
}
.menu a{
  color : white;
  padding: 10px;
}
</style>

 

 

'개발 > vue' 카테고리의 다른 글

vue+tailwind  (0) 2023.02.07
Vue.js 설치 실행  (0) 2023.02.02
크롬 앱 만들기 (노마드코더)  (0) 2023.01.30
JS-HTML  (0) 2023.01.25

1. oracle jdk 설치 - 내는 이거 되있어서 2번부터함 

2. node.js 설치

3. vue.js 설치 

$ npm install -g @vue/cli

이거 작성하면 되는데 난 안되서 앞에 sudo 붙혀서 해줌 

설치성공

$ vue create project 

뷰 프로젝트 만들어줌

서버실행 

$ cd project

$ npm run serve

localhost:8080 성공~

'개발 > vue' 카테고리의 다른 글

vue+tailwind  (0) 2023.02.07
Vue.js  (0) 2023.02.03
크롬 앱 만들기 (노마드코더)  (0) 2023.01.30
JS-HTML  (0) 2023.01.25

style.css

html, body {
    height: 100%;
}

#clock {
    font-size: 50px;
    padding-top: 70px;
}

#greeting {
    font-size: 25px;
    color: aliceblue;
}

.whiteFont {
    color: rgb(255, 255, 255);
}

.container {
    height: 100%;
    background-color: rgb(0,0,0, 0.6);
    top: 0;
}

::placeholder{
    color: rgb(256, 256, 256, 0.6);
}

.hidden {
    display: none;
}

.js {
    text-align: center;
}
li {
    list-style: none;
}

.nameBlank {
    border: none; 
    background-color: transparent; 
    height: 40px; 
    width: 500px; 
    font-size: 20px;
    outline: none;
}

.y-btn {
    border: none;
    font-weight: 600;
    padding: 3px 6px;
}

.y-btn-color {
    color: #000000;
}

.ML20 {
    margin-left: 20px;
}

#weather {
    font-size: 20px;
}

 

background.js

const images = ["img01.jpg", "img02.jpg", "img03.jpg", "img04.jpg"];
const no = Math.floor(Math.random()*images.length);
const currentImg = `img/${images[no]}`;

document.body.style.backgroundImage = `url(${currentImg})`;
document.body.style.height = "100%";
document.body.style.backgroundSize = "cover";
document.body.style.backgroundRepeat ="no-repeat";

clock.js

const clock = document.querySelector("clock");

function getClock(){
    const date = new Date();

    let h = String(date.getHours()).padStart(2, "0");
    let m = String(date.getMinutes()).padStart(2, "0");
    let s = String(date.getSeconds()).padStart(2, "0");

    let t = `${h}:${m}:${s}`;

    clock.innerText = t;
}

getClock();
setInterval(getClock, 1000);

greeting.js

const loginForm = document.querySelector("#login-form");
    const USERNAME_KEY = "userName";
    const isUserName = (localStorage.getItem(USERNAME_KEY));
    if(isUserName === null){
        loginForm.classList.remove("hidden");
    } else {
        paintGreetings(isUserName);
        loginForm.classList.add("hidden");
    }

    
    function loginClick(event) {
        const HIDDEN_CLASSNAME = "hidden";
        event.preventDefault();
        loginForm.classList.add(HIDDEN_CLASSNAME);
        const userName = document.querySelector("#login-form input").value;
        
        const greeting = document.querySelector("#greeting");
        localStorage.setItem(USERNAME_KEY, userName);
        greeting.innerText = `Hello, ${userName}!`;

        const todoBlank = document.querySelector("#todo-form");
        todoBlank.classList.remove("hidden");

        const todoList = document.querySelector("#todo-list");
        todoList.classList.remove("hidden");
    }
    
    loginForm.addEventListener("submit", loginClick);
    
    function paintGreetings(userName){
        const HIDDEN_CLASSNAME = "hidden";
        greeting.innerText = `Hello, ${userName}!`;
        greeting.classList.remove(HIDDEN_CLASSNAME);
    }

todo.js

const todoFrom = document.getElementById("todo-form");
const todoList = document.getElementById("todo-list");

if(localStorage.getItem("userName") === null){
    todoFrom.classList.add("hidden");
    todoList.classList.add("hidden");
} else {
    todoFrom.classList.remove("hidden");
    todoList.classList.remove("hidden");
}

todoFrom.addEventListener("submit", todoSubmit);

function todoSubmit(event) {
    event.preventDefault();
    const listCount = document.querySelector("#todo-list").childElementCount;
 
    const todo = document.querySelector("#todo-form input").value;
    addTodo(todo);
}

function addTodo(todo) {
    const li = document.createElement("li");
    const span = document.createElement("span");
    const button = document.createElement("button");
    span.innerText = todo;
    button.innerText = "x";
    button.classList.add("y-btn");
    button.classList.add("y-btn-color");
    button.classList.add("ML20");

    button.addEventListener("click", deleteTodo);
    li.appendChild(span);
    li.appendChild(button);

    const todoList = document.getElementById("todo-list");
    todoList.appendChild(li);

    document.querySelector("#todo-form input").value = "";

    updateTodoList();
}

function deleteTodo(event) {
    const li = event.target.parentElement;
    li.remove();

    updateTodoList();
}

function updateTodoList() {
    const todos = [];

    const todoList = document.getElementById("todo-list");
    const todoListCount = todoList.childElementCount;
    const todoResult = document.querySelectorAll("#todo-list li span");

    for (let i = 0; i < todoListCount; i++) {
        todos.push(todoResult[i].innerText);
    }

    saveInStorage(JSON.stringify(todos));
}

function saveInStorage(todos) {
    localStorage.setItem("todos", todos);
}

showTodos();

function showTodos() {
    const todos = JSON.parse(localStorage.getItem("todos"));
    
    if(localStorage.getItem("todos") !== null){
        const parseTodos = JSON.parse(localStorage.getItem("todos"));
        parseTodos.forEach((item) => callSavedTodos(item));
    }
}

function callSavedTodos(item) {
    const li = document.createElement("li");
    const span = document.createElement("span");
    const button = document.createElement("button");
    span.innerText = item;
    button.innerText = "x";
    button.classList.add("y-btn");
    button.classList.add("y-btn-color");
    button.classList.add("ML20");
    button.addEventListener("click", deleteTodo);
    li.appendChild(span);
    li.appendChild(button);
    todoList.appendChild(li);
}

weather.js

const weather = document.querySelector("#weather span:first-child");
const city = document.querySelector("#weather span:last-child");
const API_KEY="7ae887e0190dd721c973671081d81c73";

function onGeoOk(position){
    const lat = position.coords.latitude;
    const lon = position.coords.longitude;
    console.log("You live in", lat, lon);
    const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}`;

    fetch(url)
        .then((response) => response.json())
        .then((data) => {
            const weather = document.querySelector("#weather span:first-child");
            const city = document.querySelector("#weather span:last-child");

            city.innerText = `@ ${data.name}`;
            const tmp = (data.main.temp).toFixed(1);
            weather.innerText = `${data.weather[0].main}  ${tmp}°`;
        });
}

function onGeoError(){
    alert("Can't find you. No weather for you.");
}


navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatiable" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Momentum</title>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <div class="container">
        <div id="weather" class="whiteFont" style="position: absolute; top:0; right:20px;">
            <span></span>
            <span></span>
        </div>
        
        <h2 id="clock" class="js whiteFont"></h2>
        <h1 id="greeting" class="js fontShadow"></h1>
        <form id="login-form" class="js">
            <input class="js nameBlank whiteFont" type="text" placeholder="Please write your name" required>
        </form>
        <form id="todo-form" class="js">
            <input type="text" class="nameBlank js whiteFont" placeholder="Write a todo" required>
        </form>
        <ul id="todo-list" class="js whiteFont" style="font-size: 30px;">
        </ul>
        
        <!-- <div id="quote" class="js fontShadow" style="position: absolute; bottom: 20px; left: 50%; transform: translate(-50%, 0);">
            <span style="font-size: 25px;"></span>
            <span></span>
        </div> -->
        <div id="weather">
            <span></span>
            <span></span>
        </div>
    </div>
    <script src="js/greeting.js"></script>
    <script src="js/clock.js"></script>
    <!-- <script src="js/quotes.js"></script> -->
    <script src="js/background.js"></script>
    <script src="js/todo.js"></script>
    <script src="js/weather.js"></script>
</body>
</html>

 

 

 

날씨 허용해주면 이래뜸

'개발 > vue' 카테고리의 다른 글

vue+tailwind  (0) 2023.02.07
Vue.js  (0) 2023.02.03
Vue.js 설치 실행  (0) 2023.02.02
JS-HTML  (0) 2023.01.25

#01

console창에서 해당 페이지의 Index.html title을 확인할 수 있음
title을 바꿀수도 있음 index.html에도 수정 내용이 저장됨

index.html

First App

Grab me!

왓더?? 여기에 그냥 친다고 다나온다 이게 무슨일임??? 여기가 어디냐고?? index.html 밖인데 이게 무슨ㅇ리이냐?

app.js

const title = document.getElementById("title"); //getElementById함수 통해 id로 element 가져올 수 있음

title. innerText = "Got you!"

console.log(title.id);
console.log(title.className);

😀getElementById("") 이안에 id를 html에 있는 id와 맞춰줘야 innerText가 null이라는 오류가 안뜸

실행화면

//querySelector : .hello h1 .div h1 과 같이 element를 검색할 수 있게 해줌 
const title = document.querySelector(".hello h1");
//const title = document.getElementById(".hello h1");

title.innerText = "Hello!"; //이렇게 하면 Grab 1!이게 또 없어짐 

console.log(title);
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css"/>   <!--css와 연결--> 
    <title>First App</title>
</head>
<body>
    <div class="hello">
        <h1>Grab me1!</h1>
    </div>   
    <div class="hello">
        <h1>Grab me2!</h1>
    </div>   
    <div class="hello">
        <h1>Grab me3!</h1>
    </div>   
    <div class="hello">
        <h1>Grab me4!</h1>
    </div>   
    <script src="app.js"></script>
</body>
</html>

왓더?? 여기에 그냥 친다고 다나온다 이게 무슨일임???
여기가 어디냐고?? index.html <html></html> 밖인데 이게 무슨ㅇ리이냐?

#02 event

const title = document.querySelector("div.hello:first-child h1");

console.dir(title);
console.log(title);

function handleTitleClick(){
    console.log("title was clicked!");	//title클릭시 콘솔에 이 문장 뜸
	title.style.color="blue";	//title클릭시 폰트색상 blue로 바뀜
}

title.addEventListener("click", handleTitleClick);   //click이벤트

 

function handleMouseEnter(){
    console.log("mouse is here!"); 
    title.innerText = "mouse is here!"; //마우스 접근하면 title이 이텍스트로 바뀜
}

function handleMouseLeave(){
    console.log("mouse is gone!");
    title.innerText = "mouse is gone!"; //마우스 떠날떄는 title이 이텍스트로 바뀜
}

title.addEventListener("click", handleTitleClick);   //click이벤트
title.addEventListener("mouseenter", handleMouseEnter); 
title.addEventListener("mouseleave", handleMouseLeave);

'개발 > vue' 카테고리의 다른 글

vue+tailwind  (0) 2023.02.07
Vue.js  (0) 2023.02.03
Vue.js 설치 실행  (0) 2023.02.02
크롬 앱 만들기 (노마드코더)  (0) 2023.01.30

<html, css등 관련 개념 문법 정도 간단히>

http://www.tcpschool.com/html/intro

 

코딩교육 티씨피스쿨

4차산업혁명, 코딩교육, 소프트웨어교육, 코딩기초, SW코딩, 기초코딩부터 자바 파이썬 등

tcpschool.com

<js 기본문법 잘 정리되 있음>

https://poiemaweb.com/js-syntax-basics

 

Syntax Basics | PoiemaWeb

Javascript는 interactive한 웹페이지 작성을 가능하게 한다. 예를 들면, 이벤트(e.g. 버튼 클릭, 웹페이지 로딩 완료 등)에 반응하여 HTML 요소에 접근하고 HTML 요소를 조작할 수 있다. 정적인 HTML을 동적

poiemaweb.com

<js, html, css 세부적인 강의>

https://opentutorials.org/course/3085

 

WEB2 - JavaScript - 생활코딩

수업소개 이 수업은 https://opentutorials.org 를 만들어가면서 JavaScript에 대한 지식과 경험을 동시에 채워드리기 위한 목적으로 만들어진 수업입니다.  수업대상 이 수업은 웹 페이지를 사용자와 상

opentutorials.org

<활용해서 앱 만드는>

https://nomadcoders.co/javascript-for-beginners/lectures/1705

 

All Courses – 노마드 코더 Nomad Coders

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

nomadcoders.co

 

'개발 > 졸작' 카테고리의 다른 글

npm-gyp 에러  (0) 2023.02.14
가상환경없이 OnlineJudge 커스터마이징  (0) 2023.02.09
real-project 과정  (0) 2023.02.06
참고자료  (0) 2023.02.06
JS-console  (0) 2023.01.25

#01 

js - console에서 사용가능 

console을 건들이면 브라우저에 반응이 됨 ( 엔터 쳐서 실행 가능)

console창을 수정해본 결과

긴 코드를 작성하기에는 console이 적합하지 않음 → 파일을 만들어 사용하는 것이 좋음 

 

브라우저는 HTML을 열고, HTML은 CSS와 js를 가져오는 형식 

html파일을 브라우저에서 오픈

 

- html 파일에서 !를 해주면 기본값으로 세팅 

- <!--css와 연결-->    //html 파일 주석

- //js 주석

 

Index.html에 아래와 같이 script내 app.js를 연동시켜주었으므로 app.js에 변경을 하면 적용됨 

 <script src="app.js"></script>

index.html의 console창

#02 const vs let 

const와 let 이용해 variable을 만들어줌 

variable 만드는 방법 

1. const [상수 : 값 바꿀 필요 없을 때 사용]
    //const인 상태서 값 바꿔주면 오류남 

2. let [값을 아래처럼 수정할때 사용 생성 시에만 적어줌]

const a=5;  //바뀌지 않는 값 의미 variable 만들어줌
const b=2;  
let myName="umin";	//값 바꿀수 있음 

console.log(a+b);    //콘솔에 log 또는 print //console창에서 확인가능 
console.log(a*b);
console.log(a/b);
console.log("hello "+myName);

myName="uminida";

console.log("your name is "+myName);

& var를 사용해도 문제는 없으나 변수인가 상수인가를 알 수 없음 (안전하지 않음) 걍 let(얘는변수), const(얘는상수) 써라 

 

#03 boolean

0 : on

1 : off

const amIFat=true;    //문자임    null:아무것도 없다 
let something;
console.log(something, amIFat); //값을 넣지 않고 log해주면 "undefined" : 공간은 있는데 들어간 값은 없다

 

#04 arrays

시작과 끝에 [] 사용 각 값 구분은 , 사용 

코드를 이렇게 입력한 것과 일일이 const해준 것 값 똑같이 나옴 

const daysOfWeek = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];

nonsense=[1, 2, "hello", false, null, true, undefined, "nico"];

//Add one more day to the array
daysOfWeek.push("sun");
//배열 중 하나 삭제 
daysOfWeek.pop("sun");

console.log(daysOfWeek, nonsense);
//배열의 5번째 문자가 알고싶다
console.log(daysOfWeek[4]);

변수명.push(""); ← add 

배열명.pop(""); ← delete

 

#04 object

array와 구분되는 점 : 각 값마다 의미를 부여할 수 있음 

ex. name : "umin" ← 이 값이 이름임을 확인가능 

const player={
    name:"umin",
    points:10,
    fat:true,
};
//object내에서는 = 사용하지 않음 
//console.log(player);
console.log(player);
//값 변경
player.fat=false;   
player.points=player.points+15;
//object 추가 
player.lastName="potato";   
console.log(player);
const player = {
    name : "umin",
    age : 98,
};

console.log(player);
console.log(player.name="uminida"); //name변경 
console.log(player);
player.sexy="soon"; //추가
console.log(player, console);

여기서 f는 function을 의미

#05 function

여러번 입력해야하는 번거로움을 없애줌 

반복 사용해야 하는 문자를 쉽게 작성할 수 있게 해줌 

console.log("Hello my name is umin");
console.log("Hello my name is siri");
console.log("Hello my name is ujin");
console.log("Hello my name is jiyu");
console.log("Hello my name is yoda");

//위처럼 직접 입력하고 변경해줘야하는 번거로움을 아래와 같이 해결할 수 있음 
//코드의 반복 줄일 수 있음 
function sayHello(nameOfPerson, age){
    console.log("Hello my name is " + nameOfPerson + " and I'm " + age);
}

sayHello("nico", 10);
sayHello("dal", 23);
sayHello("lynn", 21);
//player Object 생성 
const player={
    name: "umin",
    sayHello: function(otherPersonsName){
        console.log("hello " + otherPersonsName + " nice to meet you!");
    },
};

console.log(player.name);
player.sayHello("lynn");

위 코드 실행결과

//계산 function
function plus(firstNumber, secondNumber){
    console.log(firstNumber+secondNumber);
}
plus(8, 60);

function divide(a, b){
    console.log(a/b);
}

divide(98, 20);
const toBuy = ["potato", "tomato", "pizza"];

console.log(toBuy[2]);
toBuy[2] = "water"; //지정된 값 하나 변경
console.log(toBuy);
toBuy.push("meat"); //배열에 값 하나 추가 
console.log(toBuy);

실행결과

#06 Returns

const calculator={
    plus: function (a, b){
        alert(a+b);
    },
    minus: function (a, b){
        alert(a-b);
    },
    times: function (a, b){
        alert(a*b);
    },
    divide: function (a, b){
        alert(a/b);
    },
    power: function (a, b){
        alert(a**b);
    }
};

calculator.plus(2, 3);
calculator.divide(2, 3);
calculator.minus(2, 3);
calculator.power(2, 3);
calculator.times(2, 3);

실행결과 순서대로 계산되어 경고창으로 나타남

const calculator={
    plus: function (a, b){
        return a+b;
    },
    minus: function (a, b){
        return a-b;
    },
    times: function (a, b){
        return a*b;
    },
    divide: function (a, b){
        return a/b;
    },
    power: function (a, b){
        return a**b;
    },
};

calculator.plus(2, 3);
const plusResult = calculator.plus(2, 3);
const minusResult = calculator.minus(plusResult, 10);
const timesResult = calculator.times(10, minusResult);
const divideResult = calculator.divide(timesResult, plusResult);
const powerResult = calculator.power(divideResult, minusResult);

위 코드 실행결과로 콘솔 내에서 직접 함수내용 입력통해 값 얻어낼 수 있음

 

#07 parseInt 

const age = prompt("How old are you?"); //age를 입력받기 위한 prompt 명령어

//입력되는 모든 값 number로
parseInt(15)

//typeof 명령어를 통해 문자형태를 확인할 수 있음 
console.log(typeof age, typeof parseInt(age));

prompt명령어를 통해서 입력창이 뜸
입력되는 문자는 string으로 인식되고 parseInt()를 통해 number로 변환되었기에 number가 된다

😀NaN : Not a Number
 
 
#08 if~else 조건문
///형태
//condition은 boolean(true or false)으로 구분 가능해야함
if(condition){
    condition === true
} else {
    condition === false
}
if(isNaN(age)){ //age가 number가 아닐경우 console에 출력됨 
    console.log("Please write a number");
} else {    //제대로 입력되었을 경우에 출력됨 
    console.log("Thank you for writing your age.");
}

=> prompt창에 숫자가 입력되면 if문의 내용이 출력되고 숫자외의 문자가 입력되면 else문의 내용이 출력된다.

 

const age = parseInt(prompt("How old are you?"));

if(isNaN(age) || age < 0){ //둘 중 하나만 true여도 됨 || or 기호 
    console.log("Please write a real positive number"); 
} else if (age<18) {    //제대로 입력되었을 경우
    console.log("You are too young."); 
} else if (age >= 18 && age <=50) { //둘다 true여야 함 && and 기호(둘다) 
    console.log("You can drink");   
} else if (age>50 && age<=80){ 
    console.log("You should exercise"); 
} else{  
    console.log("You can do wharever you want."); 
}

true || true === true
false || true === true
true || false === true
false || false === false
 

true && true === true
false && true === false
true && false === false
false && false === false

위 코드의 경우 else if 문이 중첩되어 age==100 일 경우의 출력문이 출력되지 않는다

'개발 > 졸작' 카테고리의 다른 글

npm-gyp 에러  (0) 2023.02.14
가상환경없이 OnlineJudge 커스터마이징  (0) 2023.02.09
real-project 과정  (0) 2023.02.06
참고자료  (0) 2023.02.06
自己開發  (0) 2023.01.25

+ Recent posts