반응형

하위컴포넌트 -> 상위컴포넌트로 이벤트&데이터 전달하기

 


1. 자식 컴포넌트의 이벤트 내용에 다음 내용 추가

this.$emit( ' 상위로 전달할 이벤트명 ' , 데이터 ) ;

 this.$emit('update',this.childTime);

이벤트명은 임의로 적어주고 데이터는 전달할 데이터

 

2. 상위컴포넌트의 <하위 컴포넌트>명시 부분에 이벤트 핸들러 추가

@하위에서 전달받을 이벤트명="전달받고 실행할 이벤트"

 <setTime @update="timeChanged"/>

실행할 이벤트는 상위 컴포넌트에서 명시하면 된다.

 timeChanged(childTime){ //전달받은 데이터
    console.log("이벤트전달");
	this.parentTime=childTime;
}

전체 예시 소스

하위 컴포넌트

<template>
    <div id="setTime">
    {{childTime}}
        <button class="minusBtn" @click='setValue' value="-5">-5분</button> 
    </div>
</template>

<script>
export default {
  name: 'setTime',
  data(){
    return{
        childTime:'',
    }
  },
  methods:{
    setValue(){
         this.$emit('update',this.time); //상위 컴포넌트에 이벤트, 데이터 전달
    },
  }
}
</script>

 

상위 컴포넌트

<template>
    <div id="managerMain">
        <div>현재 {{time}} 분</div>
            <setTime @update="timeChanged"/> //이벤트 명시
    </div>
</template>


<script>
import setTime from '@/components/manager_setTime.vue'

export default {
   name: 'managerMain',
   components: {
    setTime
   },
   data(){
    return{
        parentTime:''
    }
   },
   methods:{
    timeChanged(childTime){ //전달받은 데이터
    console.log("이벤트전달");
        this.parentTime=childTime;
    }
   }
}

</script>
반응형
반응형
//클릭한 요소 가져오기
let dv = event.currentTarget;

//클릭한 요소의 className 가져오기
dv.className;
//클릭한 요소의 style 속성 손보기
dv.style.backgroundColor;

//클릭한 요소의 하위 DOM요소 찾기(하위 요소 중 input 타입 찾기)
//input이 여러개라면 맨 처음 하나만 가져온다
dv.querySelector('input');

//특정 요소 모두 찾기
dv.querySelectorAll();

//id가 modal인 요소 찾기
dv.querySelector('#modal');

//클릭한 요소의 부모 요소 찾기
dv.parentNode;

//클릭한 요소의 자식 요소 찾기
dv.children

//자식요소가 여러개다?
dv.children[i]

//선택한 요소의 text 가져오기
dv.innerText 
dv.outerText
반응형
반응형

1. 프로젝트 폴더 내에서 로컬 repository 추가 

$ git init

결과) Initialized empty Git repository in D:/mtMap/.git/

 

2. git 원격저장소 설정

$ git remote add [remote이름]  [원격 repository url]

예시
$ git remote add mytest https://github.com/h92218/mytest.git

 

3. 원격저장소 설정한거 확인

$ git remote

결과) remote이름 표시됨

 

4. git에 올릴 파일 확인

$ git status

결과 ) 파일들 상태 표시 

5. 파일 추가

$ git add -A

-A는 모든 파일 추가임

다시 한번 git status로 확인해보면

 

6. 커밋하기

$ git commit -m "message"

 

7. 푸시하기

$ git push [remote 이름]

예시
$ git push mytest


fatal: The current branch main has no upstream branch.
To push the current branch and set the remote as upstream, use

    git push --set-upstream mt main

근데 아마 최초 푸시면 upstream으로 하라는 문구가 뜰 것.

해주면 됨.

$ git push --set-upstream mt main

Git global setup : 깃 전체 설정입니다~

git config --global user.name "userName"
git config --global user.email "userName@gmail.com"

Create a new repository : 레포지토리를 새로 생성하고 업로드하는 경우입니다~

git clone http://git 레포지토리 주소~~
git switch -c main
touch README.md
git add README.md
git commit -m "add README"
git push -u origin main

Push an existing folder : 레포지토리는 존재하고 git 업로드를 최초로 하는 경우입니다.

git init --initial-branch=main
git remote add origin http://git레포지토리주소~
git add .
git commit -m "Initial commit"
git push -u origin main

 

Push an existing Git repository : 사용하던 레포지토리에서 다른 레포지토리로 전환하여 업로드하는 경우

git remote rename origin old-origin
git remote add origin http://git레포지토리주소
git push -u origin --all
git push -u origin --tags

 


github에서 git repository 폴더 화살표 / 디렉토리 화살표 오류 

 

GitHub(깃허브) - 디렉토리에 화살표 표시(폴더 클릭이 안될 때)

📎 GitHub 디렉토리 화살표 표시 -> 폴더 접근 불가능 깃허브에서 한 디렉토리에 다른 디렉토리를 추가하는 도중 위와 같이 디렉토리에 화살표 표시가 생기고, 디렉토리에 접근이 되지않는 문제

zzang9ha.tistory.com

 


CRLF will be replaced error

 

Git 에러 CRLF will be replaced by LF (혹은 반대) 핸들링하는 방법

맥/리눅스 이용 개발자와 윈도우 개발자가 협업할 때 왜 발생할까? 터미널에 git 명령어를 입력했는데 다음과 같은 에러가 뜨는 경우가 있다: ```bash warning: CRLF will be replaced by LF in some/file

blog.jaeyoon.io

git config --global core.autocrlf true

 


non-fast-forward 에러

$ git push -u project master
To http://00.000.0.000:8090/project.git
 ! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'http://00.000.0.000:8090/project.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

원격 분기의 변경 내용을 로컬로 변경한 내용과 페치하고 병합하여 이 문제를 해결할 수 있습니다.

$ git fetch origin
# Fetches updates made to an online repository
$ git merge origin YOUR_BRANCH_NAME
# Merges updates made online with your local work

또는 두 명령을 한 번에 모두 수행하는 데만 git pull을 사용할 수 있습니다.

$ git pull origin YOUR_BRANCH_NAME
# Grabs online updates and merges them with your local work

참고

https://docs.github.com/ko/get-started/using-git/dealing-with-non-fast-forward-errors


fatal: refusing to merge unrelated histories

git pull origin mybranch --allow-unrelated-histories

이 명령 옵션은 이미 존재하는 두 프로젝트의 기록(history)을 저장하는 드문 상황에 사용된다고 한다. 즉, git에서는 서로 관련 기록이 없는 이질적인 두 프로젝트를 병합할 때 기본적으로 거부하는데, 이것을 허용해 주는 것이다.

참고

https://gdtbgl93.tistory.com/63

 


 Already up to date

alreay up to date 라면서 pull 안 될 때

$ git fetch --all
$ git reset --hard origin/master


git reset :  HEAD의 포인터를 특정 위치로 옮기는 명령어
--hard 옵션 :  이전 커밋으로 돌아가기. 그 커밋 이후에 내용들은 삭제됨.
--mixed 옵션 : 커밋을 이동함. 변경 이력이 모두 삭제되지만 스테이지에 코드가 남아있음. 이 코드를 add 후 커밋하면 됨.
--soft 옵션 :  mixed 옵션과 같지만 이미 스테이징 되어있음. 이 말은, add 없이 바로 커밋하면 된다~~

https://chanos.tistory.com/entry/GIT-git-pull-%EC%8B%9C-merge-%EC%98%A4%EB%A5%98-%EB%B0%9C%EC%83%9D%ED%96%88%EC%9D%84-%EB%95%8C-%EA%B0%95%EC%A0%9C%EB%A1%9C-%EB%8D%AE%EC%96%B4%EC%93%B0%EB%8A%94-%EB%B0%A9%EB%B2%95-git-fetch-reset-pull

반응형
반응형

git에서 clone받아 npm run serve 입력을 했는데 오류가 뜨면서 안된다.... ㅠ ㅠ

D:\takoyaki23\front>npm run serve

> front@0.1.0 serve D:\takoyaki23\front
> vue-cli-service serve

'vue-cli-service'은(는) 내부 또는 외부 명령, 실행할 수 있는 프로그램, 또는
배치 파일이 아닙니다.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! front@0.1.0 serve: `vue-cli-service serve`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the front@0.1.0 serve script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\heirr\AppData\Roaming\npm-cache\_logs\2021-09-30T12_13_34_121Z-debug.log

 

>>>>해결방법

1. npm cache clean --force 입력

2. node modules 삭제 후 npm install로 재설치

반응형
반응형

redis 다운로드 / 설치

 

Release 3.2.100 · microsoftarchive/redis

This is the first release of Redis on Windows 3.2. This release is based on antirez/redis/3.2.1 plus some Windows specific fixes. It has passed all the standard tests but it hasn't been tested in a...

github.com

 

설치 완료가 되면 CMD창을 열어 다음 내용을 확인

C:\Program Files\Redis>netstat -an | findstr 6379
  TCP    127.0.0.1:6379         0.0.0.0:0              LISTENING

 

redis 설치 폴더로 이동하여 다음 실행

C:\Program Files\Redis>redis-cli
127.0.0.1:6379>

 

key - value 생성 테스트. 조회가 안 되는 경우 nil 을 반환한다.

127.0.0.1:6379> set testkey testvalue
OK

127.0.0.1:6379> get testkey
"testvalue"

127.0.0.1:6379> get geeee
(nil)

redis 툴 다운로드

 

P3X Redis UI | Apps | Electron

A very functional handy database GUI and works in your pocket on the responsive web or as a desktop app.

www.electronjs.org

>>P3X RedisUI를 사용이 불가한 것 같다.

아래 툴을 다운받으면 될듯 

https://redis.com/redis-enterprise/redis-insight/

 

RedisInsight | The Best Redis GUI

RedisInsight provides an intuitive and efficient graphical interface for Redis, allowing you to interact with your databases and manage your data.

redis.com

왼쪽의 download 버튼 클릭하여 설치 

 

설치가 완료되면 UI창이 뜬다.

ADD A CONNECTION 어쩌구를 눌러 연결을 추가한다.

 

NEW CONNECTION 선택

 

Name : 연결이름

Hostname : 연결 대상 주소 

Port : 기본은 6379

Username / Password : 있는 경우 입력 

입력 후 Add를 눌러 추가한다.

 

완료가 되면 Conenctions 목록에 생기는데 

왼쪽 아래에서 선택하여 연결을 해주자 

 

연결되면 CONNECTED 상태로 바뀜

 

 

왼쪽 상단의 툴바에서 Home으로 들어간다.

 

 

그럼 아까 설정한 key와 value가 보인다. 

반응형

'코딩 관련 > redis' 카테고리의 다른 글

Springboot redis 연동하기  (0) 2023.02.05
반응형

Spring Boot & Vue 환경에서 

API 호출에 실패했는데, Status Code를 보니 

431 Request Header Fields Too Large 이었다.

 

vue 폴더 밑의 vue.config.js 에서 proxy 설정을 제대로 안했음

proxy 경로를 백엔드 서버에서 사용하는 포트(8080)로 해놓아야 했음.

module.exports = {
  outputDir: "../src/main/resources/static",
  indexPath: "../static/index.html",
  devServer: {
    proxy: "http://localhost:8080"
  },
  chainWebpack: config => {
    const svgRule = config.module.rule("svg");
    svgRule.uses.clear();
    svgRule.use("vue-svg-loader").loader("vue-svg-loader");
  }
};

바꿔주고 npm run serve로 재시작하니 잘 된다.

 


431 오류 관련 참고

https://www.okta.com/identity-101/http-error-431/

 

HTTP Error 431: Definition, Status, Causes & Solutions | Okta

HTTP error 431 shows the status code request header fields too large. Learn how to correct the different issues that generate error 431.

www.okta.com

 

반응형
반응형

Spring 환경에서 mybatis로 postgresql 연동하여 사용하는 환경.


수정 전 쿼리

 <select id="selectCount" parameterType="com.export.model.DataDto" resultType="Integer">
        SELECT COUNT(*)
        FROM ${tableName}
        WHERE ${dataTimeColumn} BETWEEN #{startTime} AND #{endTime}
</select>

where 절에 시간으로 조건을 줬는데... 에러가 났다.

Cause: org.postgresql.util.PSQLException: ERROR: operator does not exist: timestamp without time zone >= character varying

dataTimeColumn 컬럼은 timestamp 타입이라...

timestamp without time zone 타입이랑 character 타입이랑 연산이 안 된다는 것 같다.

 

 

해결방법 : TO_TIMESTAMP(문자열,'YYYY-MM-DD') 를 사용하여 문자열을 Date형식으로 변환해준다.

 

수정 후 쿼리

<select id="selectCount" parameterType="com.export.model.DataDto" resultType="Integer">
        SELECT COUNT(*)
        FROM ${tableName}
        WHERE ${dataTimeColumn} BETWEEN TO_TIMESTAMP(#{startTime},'YYYY-MM-DD') AND TO_TIMESTAMP(#{endTime},'YYYY-MM-DD')
</select>
반응형
반응형

Spring boot 환경에서 postgreSql DB를 연동하여 정보를 가져오려고 한다.

 

MyBatis 사용을 위한 설정 

- MyBatis 설정 <configuration></configuration >  : mybatis-config.xml 에서 설정함.

- SqlSessionFactory : DatabaseConfig.java 에서 설정함

- SQL 맵핑 <mapper></mapper> : dataMapper.xml에 쿼리문을 작성함 


1. 라이브러리

build.gradle에 의존성 추가

implementation "org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.1"
implementation "org.mybatis:mybatis-spring:1.3.1"
implementation "org.mybatis:mybatis:3.4.5"

implementation "org.postgresql:postgresql:9.4.1209.jre6"

 

2. mybatis 설정 파일 추가

resources > mybatis 밑에 mybatis-config.xml 생성

내용

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <settings>
        <setting name="jdbcTypeForNull" value="NULL" />
        <setting name="mapUnderscoreToCamelCase" value="true" />
    </settings>
</configuration>

jdbcTypeForNull : JDBC타입을 파라미터에 제공하지 않을때 null값을 처리한 JDBC타입을 명시한다. 일부 드라이버는 칼럼의 JDBC타입을 정의하도록 요구하지만 대부분은 NULL, VARCHAR 나 OTHER 처럼 일반적인 값을 사용해서 동작한다.

mapUnderscoreToCamelCase : 전통적인 데이터베이스 칼럼명 형태인 A_COLUMN을 CamelCase형태의 자바 프로퍼티명 형태인 aColumn으로 자동으로 매핑하도록 함

 

3.  jdbc datasource 설정

resources 밑에 application.yml 생성

내용

spring:
  profiles:
    active: local

---
# local development server
spring:
  profiles: local
  datasource:
    jdbc-url: jdbc:postgresql://localhost:5432/dbName
    driver-class-name: org.postgresql.Driver
    username: test
    password: test@!

 

4. DB 접속 및 sqlSession 설정

패키지 밑에 DataBaseConfig 생성

내용

package com.export.config;


import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

@Configuration
//////매퍼 xml 파일이 바라볼 패키지 설정
@MapperScan(value="com.export.mapper.*", sqlSessionFactoryRef = "sqlSessionFactory")
public class DataBaseConfig {

	/////application.yml에 설정한 정보를 가져와 dataSource 빈 생성
    @Primary
    @Bean(name = "dataSource")
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }


    @Primary
    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactoryBean(
            @Autowired @Qualifier("dataSource") DataSource dataSource,
            ApplicationContext applicationContext) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean
                .setConfigLocation(applicationContext.getResource("classpath:mybatis/mybatis-config.xml"));
        factoryBean
                .setMapperLocations(applicationContext.getResources("classpath:mybatis/mapper/*.xml"));
        return factoryBean.getObject();
    }

    @Primary
    @Bean(name = "sqlSession")
    public SqlSessionTemplate sqlSession(
            @Autowired @Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Primary
    @Bean(name = "transactionManager")
    public DataSourceTransactionManager transactionManager(
            @Autowired @Qualifier("dataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }


}

 

설정은 끝


매퍼 xml 파일 예시

resources > mybatis > mapper 밑에 매퍼 xml 파일을 만들었다.

내용 예시 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.export.mapper.DataMapper">
    <select id="select11" parameterType="DataDto" resultType="Integer">
        SELECT COUNT(*)
        FROM ${tableName}
        WHERE ${dataTimeColumn} BETWEEN TO_TIMESTAMP(#{startTime},'YYYY-MM-DD') AND TO_TIMESTAMP(#{endTime},'YYYY-MM-DD')
</select>


</mapper>
반응형
반응형

Spring Boot 환경에서 vue 설치하여 사용하기

IDE : intellij

 


1. Spring 프로젝트를 만들자

 

[SpringBoot] intellij 에서 Gradle을 포함한 SpringBoot 프로젝트 만들기

상단 메뉴바 File > New > Project Gradle, Java 선택, Next 프로젝트 이름이랑 경로 지정 프로젝트에서 build.gradle에서 의존성 설정 plugins { id 'org.springframework.boot' version '2.5.0' id 'io.sprin..

mchch.tistory.com

 

2. VUE CLI를 설치하자

 

[Vue] vue.js 설치/실행, 싱글파일 컴포넌트

1. Node.js 설치 다운로드 | Node.js Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine. nodejs.org 2. VUE CLI 전역설치 > npm install -g @vue/cli -g : 로컬 어디에서든 vue-cli를..

mchch.tistory.com

 

3. vue 프로젝트를 만들자

 

터미널에서 입력한다. > vue create '프로젝트이름'

옵션들을 선택하게 된다.

 

프리셋 선택

Default 설치는 Router가 없다

Manually 설치는 Router를 설치할 수 있다.

 

Manually 설치를 선택하면 기능을 선택할 수 있다. 

방향키로 움직이고 스페이스로 선택. Router를 넣었당

 

버전선택

 

 

모드 선택

Vue는 기본적으로 Hash 모드이며, History 모드로 사용할 것인지 선택하게 된다.

Hash 모드는 url 뒤에 #이 붙는다. History모드는 url뒤에 #이 붙지 않는다. 

아직은 잘 모르니 n으로 가자..

 

Hash Mode와 History Mode 설명

 

[Vue] vue-router에서 Hash Mode Vs History Mode 차이점은 무엇인가?

들어가기 최근 Vue 를 사용하게 되면서 Hash Mode와 History Mode에 대해서 의문점을 가지게 되었습니다. Vue.js에 router 관련된 설정을 추가하면서 다음과 같은 설정에 직면하게 되었습니다. import Vue from

happy-coding-day.tistory.com

 

나머지 항목들도 잘 모르니 일단은 기본으로 선택했다.

완료되면 디렉토리가 생긴당.

 

 

4. 뷰 프로젝트 설정

뷰 디렉토리 밑에 vue.config.js 파일을 생성한다.

 

파일 내용

module.exports = {
  //outputDir : npm run build로 빌드 시에 파일이 생성되는 위치
  outputDir: "../src/main/resources/static",
  //indexPath : index.html 파일이 생성될 위치
  indexPath: "../static/index.html",
  //SpringBoot 서버 접속 주소
  devServer: {
    proxy: "http://localhost:8080"
  },
  chainWebpack: config => {
    const svgRule = config.module.rule("svg");
    svgRule.uses.clear();
    svgRule.use("vue-svg-loader").loader("vue-svg-loader");
  }
};

 

 

5. 빌드

터미널에서 vue 프로젝트 디렉토리로 이동한 뒤에

> npm run build 입력

완료되니 resources 밑에 index.html과 소스들이 생겼다.

안생겼으면 껐다가 다시 열기 

 

6. 실행

spring 을 실행하고 

터미널에서 >npm run serve 를 입력하고 나면 완료된다.

 

반응형
반응형

머 이런 값을 가진 Map 이 있다고하자

{a=1,b=2,c=null}

 

c라는 key로 접근 -> value가 null

d라는 key로 접근 -> key가 없어서 NullPointerException

map.get("c")  //null값 
map.get("d") //NullPointerException

 

get 대신에 getOrDefault를 사용하면 된다. key 뒤에는 null일 경우 사용할 디폴트값을 지정해준다.

map.getOrDefault("c","-999");
map.getOrDefault("d","-999");​
반응형

+ Recent posts