22.06.08 Vue.js 공부 정리

www: 서브도메인
서브도메인은 무한정 뽑아낼 수 있음
/안에 들어있는 정보: 파라미터
쿼리스트링: 검색필터. ?뒤쪽은 쿼리스트링이 나오면 key, value로 쪼개기
https://www.omdbapi.com?apikey=7035c60c&s=frozen&page=3

Vite.js 실행

npm create vite@latest 생성할폴더이름

vue router도 할거라 설치해주기
npm i -D vie-router
eslint랑 sass 설치해주기
npm i -D eslint eslint-plugin-vue sass

vite.config.js

경로별칭 지정해주기

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: [{
      find: '~',
      replacement: `${__dirname}/src`
    }]
  }
})

.eslintrc.json

src폴더안에 생성해주기

{
  "env": {
    "browser": true,
    "node": true
  },
  "extends": [
    "eslint:recommended",
    "plugin:vue/vue3-recommended"
  ],
  "rules": {
    "semi": ["error", "never"],
    "quotes": ["error", "single"],
    "eol-last": ["error", "always"],

    "vue/html-closing-bracket-newline": ["error", {
      "singleline": "never",
      "multiline": "never"
    }],
    "vue/html-self-closing": ["error", {
      "html": {
        "void": "always",
        "normal": "never",
        "component": "always"
      },
      "svg": "always",
      "math": "always"
    }],
    "vue/comment-directive": "off",
    "vue/multi-word-component-names": "off"
  }
}

src -> routes 폴더 생성
route = page

routes 폴더 안에 index.js 파일 생성 후
vue-router에서 객체분해할당 createRouter, createWebHistory 가져오기

import { createRouter, createWebHistory } from 'vue-router' 

가져와서 생성한 결과를 export로 내보내기
제공옵션 2개
mode 2개: hashmode, historymode(로컬에서 그냥 가능하나 베포할때 서버에 기본셋팅필요)

export default createRouter({
  history: createWebHistory()
  routes: [
    {
      path: '/' (메인페이지)
      component: 
    }
  ]
})
예시)
routes안에 Home.vue 파일 만들었을 시 연결하는 방법
import Home from './Home.vue'
{
  path: '/' 
  component: Home
}

만들어진 index.js를 main.js에 연결시켜주자
import router from './routes'
.use(router)

연결이 됐으면 router가 화면에 보여지게끔 연결해줘야하는데
App.vue 파일에 가서 
<RouterView />로 연결
`RouterView` 화면에 보여질 영역
fetch메소드 기본구조
async name() {
  fetch 나온 결과 res로 받고
      let res = await fetch('')
  res.json을 res로 반환 받고
      res = await res.json()
      console.log(res)
}

끄적

이미지 사이즈가 다 다를 경우 백그라운드 이미지로 주기
scoped는 현재 페이지 내에서만 영향이 가도록설정

<style scoped lang="scss">
.poster {
  width: 400px;
  height: calc(400px * 3 / 2);
  background-size: cover;
  background-color: lightgray;
}
</style>

vue router에서 제공하는 객체

$route: 정보를 담고있는
$router : 페이지 이동관련. -> html // router.push() -> JS

router.push(name:'지정한이름써주기')
router.push(경로써줘도됨)
router.go(1) 한번앞으로, router.go(-1) 한번뒤로

:sunny -> 동적인 정보 제공할때 콜론기호(:)사용
{
      path: '/:sunny'
      component: Home
}
:sunny정보를 가져올때 {this.$route.params.sunny}

404page

제일 아래쪽에 써줘야함
/:notFound(.) 자바스크립트 정규표현식규칙

{
      path: '/:notFound(.*)*',
      component: NotFound
}

nested routes

자식주소
children: [
  {
    path: '',
    component: ''
  }
]

Header.vue에 라우터링크 모아넣기

RouterLink를 배열화 시켜서 for in 문으로 쪼개기

data() {
  return {
    navigations: [
      { path: '/', name: '클릭당할이름'}
      { path: '/', name: '클릭당할이름'}
      { path: '/', name: '클릭당할이름'}
      { path: '/', name: '클릭당할이름'}
    ]
  }
}

Named view

파스칼케이스
객체데이터는 순서가 존재하지 않는다

components: {
        TheHeader,
        default: Movie
      }
components: {
        // 데이터이름과 속성의 이름이 같다
        TheHeader,
        default: Home,
      }

Redirect

// 페이지를 다시 팅겨낸다?. 임시로 보수중일때활용

redirect: '/fix'

Route Meta Fields

내용을 담을 수 있음

meta: {
        auth: ture
      }
created() {
      // 페이지 정보를 들고있는 아이 $route
      // meta:{여기에 저보를 담을 수 있음}
      // [[Prototype]]: Object
      console.log(this.$route)
}

Navigation Guards

모든 페이지에 접속하기 전, 모든페이지에서 빠져나올 때
네비게이션 가드를 통해 사용할 수 있음

Global Before Gurads(모든페이지에 접속하기 직전에)
라우터가드가 검문소 역할(걸러내준다?)

//라우터가드를 만들자
//main.js에도 넣어주는거 까먹지 말기
// createRouter를 router변수에 담아 실행

import router from './index.js'
// router.beforeEach((to, from) to는 어디로 들어갈건지, from은 어디에서 출발
// return 키워드 필수! true, false
router.beforeEach(to => {
  //to는 내가 접근하고자 하는 정보의 객체를 들고 있음
  console.log(to)
  console.log(to.meta.auth)
  // JSON은 기본적으로 문자형식. 로컬스토리지에 키(currentUser)벨류(name,age)값 직접 적고, 콘솔찍어보기
  console.log(localStorage.getItem('currentUser'))


  if (to.meta.auth) {
    console.log(JSON.parse(localStorage.getItem('currentUser')))
    const {
      name
    } = JSON.parse(localStorage.getItem('currentUser') || '{}')
    if (name) {
      return true
    } else {
      // return '/login'
      return '/'
    }
  }

  //boolean값을 반환해줘야함
  return true
})

페이지 스크롤 scrollBehavior

  // 페이지가 바뀔 때 스크롤을 어느위치에 둘 것인지
  // 페이지 관리 시 필 수 옵션
  scrollBehavior: () => ({
    top: 0
  })
//   아래코드를 축약
//   scrollBehavior: () => {
//       return {
//       top: 0
//       }
//   }

'프론트엔드 > Vue.js' 카테고리의 다른 글

Vue.js  (0) 2022.06.06
(22.05.26)Vue.js  (0) 2022.05.26
(22.05.25) Vue.js  (0) 2022.05.25
(22.05.23) Vue.js  (0) 2022.05.23

+ Recent posts