반응형

1. 설치

npm i --save bootstrap
npm i --save @popperjs/core  // 부트스트랩 실행에 필요

2. main.js에 두줄만 Import하면 됨

import { createApp } from 'vue'
import App from './App.vue'
import router from './router/index.js'

// 아래 두줄만 넣으면 된다.
import 'bootstrap/dist/css/bootstrap.min.css'
import 'bootstrap'

createApp(App)
.use(router)
.mount('#app')

 

*** bootstrap-vue 적용하기

npm install vue bootstrap-vue bootstrap

 

이제 main.js에  import

import BootstrapVue from 'bootstrap-vue'
import 'bootstrap/dist/css/bootstrap.min.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'

Vue.use(BootstrapVue)
반응형
반응형

state : data

getters : computed

mutations : methods

actions : methods(비동기)

Vuex action에서의 활용

context.state

context.getters

context.commit (mutation의 함수 사용시)

context.dispatch (action의 함수 사용시)

Vue 컴포넌트에서 Vuex Helper 사용

...mapState('모듈',[

   '상태1','상태2'

])   ===> computed에서 사용

...mapGetters('모듈',[

   '상태1','상태2'

])  ===> computed에서 사용

...mapMutations('모듈',[

   '상태1','상태2'

])  ===> methods에서 사용

...mapActions('모듈',[

   '상태1','상태2'

])  ===> methods에서 사용

 

반응형
반응형

1. routes 수정

/movie/#123456과 같이 ID를 입력받을 수 있도록 수정

import { createRouter, createWebHashHistory} from 'vue-router'
import Home from './MyHome.vue'
import Movie from './MyMovie.vue'
import About from './MyAbout.vue'

export default createRouter({
  // Hash, History --> Hash mode 사용 예정
  history: createWebHashHistory(),
  // pages
  routes:[
    {
      path:'/',
      component: Home
    },
    {
      path:'/movie/:id',
      component: Movie
    },
    {
      path:'/about',
      component: About
    }

  ]
})

2. ./store/movie.js :단일 영화 상세정보 가져오기

import axios from 'axios';
import _uniqBy from 'lodash/uniqBy'

export default {
  // module화 부분
  namespaced:true,
  // 실제 데이터
  state: () => {
    return {
      movies:[],
      message:'Search for the movie title!',
      loading: false,
      theMovie: {

      }
    }
  },
  // computed와 동일
  getters:{
    movieIds(state){
      return state.movies.map(m => m.imdbID)
    }
  },
  // methods와 동일
  // 변이: state 데이터 변경
  mutations:{
    updateState(state, payload){
      // ['movies','message','loading']
      Object.keys(payload).forEach(key => {
        // state.movies = payload.movies
        // state.message = payload.message
        // state.loading = payload.loading
        state[key] = payload[key]
      })
    },
    resetMovies(state){
      state.movies =[]
    }
  },
  // 기본적으로 비동기 처리
  actions: {
    async searchMovies(context, payload){
      // Search 실행중이면 함수 종료
      if (context.state.loading) return
      
      // message 초기화
      context.commit('updateState', {
        message: '',
        loading: true
      });
      try {
        const res = await _fetchMovie({
          ...payload,
          page: 1,
        });
        const { Search, totalResults } = res.data
        console.log(totalResults)
        context.commit('updateState', {
          movies: _uniqBy(Search, 'imdbID')
        })
        console.log(totalResults)
        console.log(typeof totalResults)
  
        const total = parseInt(totalResults, 10) //문자열 totalResults를 10진수 정수로 변경
        const pageLength = Math.ceil(total / 10) //한페이지에 10개씩
  
        if(pageLength > 1) {
          for(let page = 2; page <= pageLength; page+=1){
            if(page > payload.number / 10) break
            const res = await _fetchMovie({
              ...payload,
              page
            });
            const { Search } = res.data
            context.commit('updateState',{
              movies: [
                ...context.state.movies, 
                ..._uniqBy(Search, 'imdbID')
              ]
            })
          }
        }
      } catch (message){
        context.commit("updateState", {
          movie: [],
          message,
        });
      } finally {
        context.commit('updateState', {
          loading: false,
        })
      }
    },
    async searchMovieWithId(context, payload){     
      if (context.state.loading) return
      
      context.commit('updateState', {
        theMovie: {}, //기존의 검색결과를 초기화
        loading: true
      })

      try{
        const res = await _fetchMovie(payload)
        context.commit('updateState', {
          theMovie:res.data
        })
      } catch (error){
        context.commit('updateState', {
          theMovie:{}
      })
      } finally {
        context.commit('updateState', {
          loading: false
        })
      }
    }
  }
}
function _fetchMovie(payload){
  const { title, type, year, page, id } = payload;
  const OMDB_API_KEY='abd6b67a'
  const url = id 
      ? `https://www.omdbapi.com/?apikey=${OMDB_API_KEY}&i=${id}`
      :`https://www.omdbapi.com/?apikey=${OMDB_API_KEY}&s=${title}&type=${type}&y=${year}&page=${page}`;

  return new Promise((resolve, reject) => {
    axios.get(url)
      .then((res)=> {
        if (res.data.Error){ // 아무 검색어 없이 엔터입력 시 에러처리
          reject(res.data.Error);
        }
        resolve(res);
      })
      .catch((err)=> {
        reject(err.message);
      });
  });
}

3. ./components/MyLoader.vue

비동기 요청시 로더 별도로 분리

<template>
  <div 
    :class="{ absolute,fixed }" 
    class="spinner-border"
    :style="{
      width: `${size}rem`,
      height: `${size}rem`,
      zIndex
    }"> 
    <svg role="status" class="inline w-8 h-8 mr-2 text-gray-200 animate-spin dark:text-gray-600 fill-yellow-400" viewBox="0 0 100 101" fill="none" xmlns="http://www.w3.org/2000/svg">
      <path d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z" fill="currentColor"/>
      <path d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z" fill="currentFill"/>
    </svg>
  </div>
</template>  

<script>
export default {
  props: {
    size: {
      type: Number,
      default: 2
    },
    absolute: {
      type: Boolean,
      default: false
    },
    fixed: {
      type: Boolean,
      default: false
    },
    zIndex: {
      type: Number,
      default: 0
    }
  }
}
</script>

<style scoped>
.spinner-border {
  margin: auto;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;  
}
.absolute {
  position: absolute;
}
.fixed {
  position: fixed;
}
</style>

3. ./routes/MyMovie.vue

Loading시 보여줄 스켈레톤 UI와 Loading후 보여줄 상세페이지

<template>
  <div class="container">
    <template v-if="loading">
      <div class="skeletons">
        <div class="skeleton poster"></div>
        <div class="specs">
          <div class="skeleton title"></div>
          <div class="skeleton spec"></div>
          <div class="skeleton plot"></div>
          <div class="skeleton etc"></div>
          <div class="skeleton etc"></div>
          <div class="skeleton etc"></div>          
        </div>      
      </div>
      <Loader 
        :size="3"
        :z-index="9"
        fixed />
    </template>
    <div v-else class="movie-details">
      <div 
        :style="{ backgroundImage: `url(${theMovie.Poster})` }"
        class="poster"></div>
      <div class="specs">
        <div class="title">
          {{ theMovie.Title }}
        </div>
        <div class="labels">
          <span>{{ theMovie.Released }}</span>
          <span>{{ theMovie.Runtime }}</span>
          <span>{{ theMovie.Country }}</span>
        </div>
        <div class="plot">
          {{ theMovie.Plot }}
        </div>
        <div class="ratings">
          <h3>Ratings</h3>
        </div>
        <div>
          <h3>Actors</h3>
          {{ theMovie.Actors}}
        </div>
        <div>
          <h3>Director</h3>
          {{ theMovie.Director }}
        </div>
        <div>
          <h3>Production</h3>
          {{ theMovie.Production }}
        </div>
        <div>
          <h3>Genre</h3>
          {{ theMovie.Genre }}
        </div>
      </div>
    </div>

  </div>
</template>

<script>
import Loader from '../components/MyLoader.vue'
export default {
  components: {
    Loader
  },
  computed: {
    theMovie() {
      return this.$store.state.movie.theMovie;
    },
    loading() {
      return this.$store.state.movie.loading
    }
  },
  created() {
    this.$store.dispatch('movie/searchMovieWithId',{
      id:this.$route.params.id
    })
  }
}
</script>

<style scoped>
.container {
  padding-top: 40px;
  margin: 0 auto;
}
.skeletons{
  display: flex;
}
.skeletons .poster {
  flex-shrink: 0;
  width: 500px;
  height: 750px;
  margin-right: 70px;
}
.skeletons .specs {
  flex-grow: 1;
}
.skeletons .skeleton {
  border-radius:  10px;
  background-color: lightgray;
}
.skeletons .title {
  width: 80%;
  height: 70px;
}
.skeletons .spec {
  width: 60%;
  height: 30px;
  margin-top: 20px;
}
.skeletons .plot {
  width: 100%;
  height: 250px;
  margin-top: 20px;
}
.skeletons .etc {
  width: 50%;
  height: 50px;
  margin-top: 20px;
}
.movie-details{
  display: flex;
  color: gray;
}
.movie-details .poster {
  flex-shrink: 0;
  width: 500px;
  height: 750px;
  margin-right: 70px;
  border-radius: 10px;
  background-color: lightgray;
  background-size: cover;
  background-position: center;
}
.movie-details .specs {
  flex-grow: 1;
}
.movie-details .specs .title {
  color: black;
  font-family: 'Oswald', sans-serif;
  font-size: 70px;
  line-height: 1;
  margin-bottom: 30px;
}
.movie-details .specs .labels {
  color: rgb(138, 138, 23);
}
.movie-details .specs .labels span::after{
  content:"\00b7";
  margin: 0 6px;
}
.movie-details .specs .labels span:last-child::after{
  display: none;
}
.movie-details .specs .plot {
  margin-top: 20px;
}
.movie-details .specs .ratings {}
.movie-details .specs h3 {
  margin: 24px 0 6px;
  color: black;
  font-family: "Oswald", sans-serif;
  font-size: 20px;
}
</style>
반응형

'Programming > Vue' 카테고리의 다른 글

Vue3 + bootstrap5 적용하기  (0) 2022.05.28
Vuex 사용  (0) 2022.05.24
Vue 영화검색사이트 기본 설치 파일  (0) 2022.05.14
Vue Tailwind CSS 적용하기  (0) 2022.05.13
Vue apache 배포 오류  (0) 2022.05.12
반응형

1.라이브러리 설치

npm i vue-router vuex bootstrap@5
npm i -D node-sass sass-loader

 

2. bootstrap 커스터마이징

- scss/main.scss 작성

- 오류 방지를 위해 maps는 주석 처리

// Required
@import "../../node_modules/bootstrap/scss/functions";

// Default variable overrides
$primary:#FDC000; //variables가 실행되기 전에 재정의되어야 함

// Required
@import "../../node_modules/bootstrap/scss/variables";
@import "../../node_modules/bootstrap/scss/mixins";
@import "../../node_modules/bootstrap/scss/root";
// @import "../../node_modules/bootstrap/scss/maps";

@import "../../node_modules/bootstrap/scss/bootstrap.scss";

 

3. Bootstrap navigation 버튼의 Pill 활성화(active) 예시

- components/Header.vue

<template>
  <header>
    <div class="nav nav-pills">
      <div v-for="nav in navigations"
        :key="nav.name"
        class="nav-item">
        <RouterLink 
          :to="nav.href"
          active-class="active"  
          class="nav-link">
          <!-- bootstrap의 nav Pill속성의 Active 클래스인 "active"로 지정 -->
          {{ nav.name }}
        </RouterLink>
      </div>
    </div>
  </header>
</template>

<script>
export default{
  data() {
    return {
      navigations:[
        {
          name:'Search',
          href:'/'
        },
        {
          name:'Movie',
          href:'/movie'
        },
        {
          name:'About',
          href:'/about'
        }
      ]
    }
  }
}
</script>
반응형
반응형

1. 설치

npm install -D tailwindcss@latest postcss@latest autoprefixer@latest

2. 활성화

npx tailwindcss init -p

 

3. ./tailwind.config.js환경설정

module.exports = {
  // content: [
  //   "./index.html",
  //   "./src/**/*.{vue,js,ts,jsx,tsx}",
  // ],
  purge:[
    "./index.html",
    "./src/**/*.{vue,js,ts,jsx,tsx}"
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

 

4. src/index.css 파일 생성 

@import "tailwindcss/base"; 
@import "tailwindcss/components"; 
@import "tailwindcss/utilities";

 

5. src/main.js적용

import { createApp } from 'vue'
import App from './App.vue'
import './index.css'

createApp(App)
.mount('#app')
반응형
반응형

Vue로 작성한 프로그램을 Build를 하고...

npm run build

 

/dist/ 폴더의 파일들을 아파치 폴더에 옮겼는데, 빈 화면이 나옵니다. index.html 파일은 보이는데 개발자 화면 확인해보니...js파일과 css파일의 경로를 인식을 못했습니다.

"/js/chunk-vendors....."처럼 되어있는데, 혹시나 해서 "."을 붙여보니 작동이 됩니다. 

동일한 오류 겪고계신 분께서는 한번 시도해보시길 바랍니다.

반응형
반응형

1. vue/cli 설치

npm i -g @vue/cli

 

2. 프로젝트 생성

vue create . //해당 폴더에 생성

 

3. 라이브러리 설치

npm i -g reset-css
npm i vuex@next

4. App.js

<template>
  <div id="app">
    <h1 id="app-title">Fruits List</h1>
    <div id="fruits-table">
      <FruitsList></FruitsList>
      <FruitsPrice></FruitsPrice>
    </div>
  </div>
</template>

<script>
// import HelloWorld from './components/HelloWorld.vue'
// import Mycom from './components/Mycom.vue';
import FruitsList from './components/FruitList.vue'
import FruitsPrice from './components/FruitPrice.vue'

export default {
  name: 'App',
  components: {
    FruitsList,
    FruitsPrice,
  }
}
</script>

<style>
  @import url("css/app.css");
</style>

 

5. /components/FruitList.vue

<!--FruitsList.vue-->
<template>
  <div id="fruits-list">
    <h1>Fruits Name</h1>
    <ul>
      <li v-for="fruit in fruits" :key=fruit>
        {{ fruit.name }}
      </li>
    </ul>
  </div>
</template>

<script>
  export default {
    // Removed Props
    computed: {
      fruits() {
        return this.$store.state.fruits
      }
    }
  }
</script>

<style></style>

 

6. /components/FruitPrice.vue

<!--FruitsPrice.vue-->
<template>
  <div id="fruits-price">
    <h1>Fruits Price</h1>
    <ul>
      <li v-for="fruit in fruits" :key="fruit">
        $ {{ fruit.price }}
      </li>
    </ul>
  </div>
</template>

<script>
  export default {
    // Removed props
    computed: {
      fruits() {
        return this.$store.state.fruits
      }
    }
  }
</script>

<style></style>

 

7. store/store.js

// store.js

import  {createStore} from 'vuex';


//export const store = createStore({
export default createStore({
  // 상태
  state: {
    fruits: [
      { name: 'Apple', price: 30 },
      { name: 'Banana', price: 40 },
      { name: 'Mango', price: 50 },
      { name: 'Orange', price: 60 },
      { name: 'Tomato', price: 70 },
      { name: 'Pineapple', price: 80 }
    ]
  }
});

8. main.js

import { createApp } from 'vue'
import App from './App.vue'
import { store } from './store/store.js'

createApp(App)
.use(store)
.mount('#app')

9. App.css

reset.css가 잘 안불러와질 때가 있네요. 설정 고치는 일이 어려워 일단 생략하고 진행합니다.

/*app.css*/
/* @import url("~reset-css/reset.css"); */
#app-title {
  color: orangered;
  font-size: 40px;
  font-weight: bold;
  text-align: center;
  padding: 40px 0 20px 0;
}
.fruits-table {
  max-width: 700px;
  margin: 0 auto;
  display: flex;
  text-align: center;
  padding: 0 20px;
}
.fruits-table li {
  padding: 20px;
  border-bottom: 1px dashed grey;
  color: white;
  list-style: none;
}
.fruits-table li:last-child { border-bottom: none; }
.fruits-table li:hover { background: rgba(255,255,255,.2); }

#fruits-list {
  background: orange;
  flex: 1;
}
#fruits-price {
  background: tomato;
  flex: 1;
}
#fruits-list h1,
#fruits-price h1 {
  font-weight: bold;
  font-size: 20px;
  padding: 20px;
  border-bottom: 1px solid;
}

반응형
반응형

 

1. 프로젝트 구성 (Template Download)

  /node_modules

  .babelrc.js

  .gitignore

  .postcssrc.js

  .babelrc.js

  .package-lock.json

  .package.json

  .webpack.config.js

 

  index.html

  /src/App.vue

  /src/main.js

  /src/assets/logo.jpg

    ㄴ/components/HelloWorld.vue

  /scss/main.scss

  /static/fabicon.ico

 

2. Package 설치

   npm i vue@next

   npm i -D vue-loader@next vue-style-loader @vue/compiler-sfc

   npm i -D file-loader

   npm i -D eslint eslint-plugin-vue babel-eslint

 

3. webpack.config.js 수정

const path = require('path')
const HtmlPlugin = require('html-webpack-plugin')
const CopyPlugin = require('copy-webpack-plugin')
const { VueLoaderPlugin } = require('vue-loader') // 추가

module.exports = {
    resolve: {
        extensions: ['.js', '.vue'], // 추가: vue 확장자 자동 인식
        alias: {
            '~': path.resolve(__dirname, 'src'),
            'assets': path.resolve(__dirname, 'src/assets')
        }
    }, 
    
	// 파일을 읽어들이기 시작하는 진입점 설정
    entry: './src/main.js',	// 엔트리 파일 인식. 번들링 결과물에 포함시킴
    output: {
    	// 현재는 path와 filename이 기본값과 동일하므로 생략 가능
    	// path: path.resolve(__dirname, 'dist'),	//절대경로 필요, 폴더명
        // filename: 'main.js',
        clean: true	// 새로 build 시 기존 필요없는 파일/폴더 삭제
    },
    
   module: {
        rules: [
            {
                test: /\.vue$/,     // 추가
                use: 'vue-loader'   // 추가
            },
            {
                test: /\.s?css$/,	// .css 또는 scss로 끝나는 파일 인식
                use: [
                    'vue-style-loader', // 추가
                    'style-loader',	// html에 삽입해주는 역할
                    'css-loader',	// 먼저 해석됨. js에서 css에서 인식하도록 해석
                    'postcss-loader',	// 공급업체 접두사 적용
                    'sass-loader'	// 가장 먼저 해석됨. js에서 scss에서 인식하도록 해석
                ]
            },
            { 
                test:/\.js$/,
                use: [
                    'babel-loader'  //바벨이 적용될 수 있도록 설정
                ]
            },
            {
                test:/\.(png|jpe?g|gif|webp)$/,
                use: 'file-loader'
            }        
        ]
    },
    
    plugins:[
    	new HtmlPlugin({
        	template: './index.html'	// 번들링 결과물에 html을 포함시킴
        }),
        new CopyPlugin({
        	patterns: [
            	{ from: 'static' }		// 번들링 결과물에 스태틱 파일을 포함시킴
            ]
        }),
        new VueLoaderPlugin()   // 추가
    ],
    
    devServer:{
    	host: 'localhost'	// 서버 호스팅 주소
    }
}

4. index.html

<!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">
    <title>Document</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/reset-css@5.0.1/reset.min.css">
</head>
<body>
  <div id="app"></div>
</body>
</html>

5. main.js

import { createApp } from 'vue'
import App from './App'

createApp(App).mount('#app')

6. App.vue

<template>
  <h1>{{ message }}</h1>
  <HelloWorld />
</template>

<script>
import HelloWorld from '~/components/HelloWorld'

export default {
  components:{
    HelloWorld
  },
  data() {
    return{
      message: 'Hello Vue!!!'
    }
  }
}
</script>

7. HelloWorld.vue

<template>
  <img src="~assets/background.png" alt="logo">
</template>

<style>
  img {
    width: 600px;
    border-radius: 10px;
  }
</style>

 

8. eslint 설정(.eslintrc.js)

module.exports = {
  env:{
    browser: true,
    node: true
  },
  extends:[
    // vue
    //'plugin:vue/vue3-essential',
    'plugin:vue/vue3-strongly-recommended',
    //'plugin:vue/vue3-recommended'
    //js
    'eslint:recommended'
  ],
  parserOptions:{
    parser: 'babel-eslint'
  },
  rules:[
    "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/html-indent": ["error", "tab", {
        attribute: 1,
        baseIndent: 1,
        closeBracket: 0,
        alignAttributesVertically: true,
        ignores: [],
      }],
  ]
}

 

9. package.json

{
  "name": "11_webpack3",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "webpack-dev-server --mode development",
    "build": "webpack --mode production"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.14.3",
    "@babel/plugin-transform-runtime": "^7.14.3",
    "@babel/preset-env": "^7.14.2",
    "@vue/compiler-sfc": "^3.0.11",
    "autoprefixer": "^10.2.5",
    "babel-eslint": "^10.1.0",
    "babel-loader": "^8.2.2",
    "copy-webpack-plugin": "^8.1.1",
    "css-loader": "^5.2.5",
    "eslint": "^7.27.0",
    "eslint-plugin-vue": "^7.9.0",
    "file-loader": "^6.2.0",
    "html-webpack-plugin": "^5.3.1",
    "postcss": "^8.2.15",
    "postcss-loader": "^5.3.0",
    "sass": "^1.32.13",
    "sass-loader": "^11.1.1",
    "style-loader": "^2.0.0",
    "vue-loader": "^16.2.0",
    "vue-style-loader": "^4.1.3",
    "webpack": "^5.37.1",
    "webpack-cli": "^4.7.0",
    "webpack-dev-server": "^4.0.0-beta.3"
  },
  "browserslist": [
    "> 1%",
    "last 2 versions"
  ],
  "dependencies": {
    "vue": "^3.0.11"
  }
}
반응형

+ Recent posts