Vue 치트 시트 3(고급)

43207 단어 webdevvuetutorial
안녕하세요 DEV.to 커뮤니티입니다!

Vue 치트 시트 시리즈가 많은 관심을 받았기 때문에 이 시리즈를 계속 게시하기로 결정했으며 거의 ​​모든 주요 초보자 항목이 이전 시리즈에서 다루어졌기 때문에 이 시리즈는 조금 더 발전될 것입니다.

일부 설명 및 코드 샘플은 Vue.js 공식 웹사이트에서 가져왔습니다. Visit Vue.js

이 기사의 일본어 버전은 https://qiita.com/_masa_u/items/d53275218cd381e1a810에 있습니다. 덕분에


.ltag__user__id__378977 .follow-action-button {
배경색: #ffffff !중요;
색상: #f50000 !중요;
테두리 색상: #f50000 !중요;
}



마사 유



Software Developer working mainly with Python, Javascript



즐기다!

내용의 테이블



  • Mixins
  • Mixin option merging
  • Global mixins


  • Custom directives
  • Custom global directives


  • Filters
  • Global filters


  • Router

  • Getting started with router
  • Router installation
  • Defining routes

  • Router links

  • Advanced routing

  • Dynamic routes
  • Reacting to dynamic routes param changes

  • 404 route
  • Asterisk routes


  • Named routes
  • Named routes with params


  • Programmatic navigation
  • Programmatic named navigation
  • Programmatic navigation with params


  • Route redirection
  • Route named redirection
  • Dynamic route redirection
  • Route redirection with params

  • Route alias


  • 믹신

    To be simple, mixins are just parts of your component stored in a separate file son it can be used again in other components.

    A mixin can look like this:

    // define a mixin object
    export const myMixin = {
      created: function () {
        this.hello()
      },
      methods: {
        hello: function () {
          console.log('Hello from mixin!')
        }
      }
    }
    

    As you see this has a created hook and a method called hello so now this mixing can be used in a component, like below:

    <script>
        import { myMixin } from './myMixin.js';
        export default {
            mixins: [myMixin]
        }
    </script>
    

    So this will function as if you wrote those hooks and methods in this component.

    Mixin 옵션 병합

    Well in case of any conflicts between a components self-assigned properties or methods and the mixin's, the component it self will be in priority, see this:

    let mixin = {
      data: function () {
        return {
          message: 'hello',
          foo: 'abc'
        }
      }
    }
    
    new Vue({
      mixins: [mixin],
      data: function () {
        return {
          message: 'goodbye',
          bar: 'def'
        }
      },
      created: function () {
        console.log(this.$data)
        // => { message: "goodbye", foo: "abc", bar: "def" }
      }
    })
    

    The way Vue handles overwriting can be changed but we will cover that in the other cheat sheet.

    글로벌 믹스인

    A global mixin is no different than a normal mixin rather than its affection scope which will include all Vue instances created.

    import Vue from 'vue';
    
    Vue.mixin({
        methods: {
            sayHi() {
                alert('Salam!');
            }
        }
    });
    
    const app = new Vue({
        el: '#app'
    });
    

    The method sayHi will be available for every component and Vue instance in the code above.

    맞춤 지시문

    As you know directives are the way Vue handles DOM. For instance v-model or v-show are directives.

    In order to define a directive you can do as below:

    <script>
        export default {
            directives: {
                focus: {
                    inserted: function (el) {
                        el.focus()
                    }
                }
            }
        }
    </script>
    

    The focus directive will be available as v-focus and can be used like this:

    <input v-focus />
    

    So the input will be focused as soon as the component renders.

    사용자 지정 글로벌 지시문

    In order for your custom directives to be available throughout your Vue instance and globally you can define it like below:

    Vue.directive('focus', {
      inserted: function (el) {
        el.focus()
      }
    })
    

    필터

    Filters are simply used to alter a value and return it.
    They can be used in both mustaches and v-bind directive.

    To define a filter in a component you can de as below:

    <script>
        export default {
            filters: {
                capitalize: function(value) {
                    if (!value) return '';
                    value = value.toString();
                    return value.charAt(0).toUpperCase() + value.slice(1);
                }
            }
        };
    </script>
    

    Then the capitalize filter can be used as below:

    <span>{{ msg | capitalize }}</span>
    

    Or in a v-bind as below:

    <a v-bind:href="url | capitalize">My capitalized link!</a>
    

    전역 필터

    Global filters are no different than normal filters but they will be defined once and can be used in every Vue instance or component.

    import Vue from 'vue';
    
    Vue.filter('focus', {
        capitalize: function(value) {
            if (!value) return '';
            value = value.toString();
            return value.charAt(0).toUpperCase() + value.slice(1);
        }
    });
    

    라우터

    Vue router is used to design a routing system on the client-side using Vue.

    라우터 시작하기

    In order to start using the router you need to install it. These are steps:

    라우터 설치

    It is recommended to install it using npm:

    npm i vue-router --save
    

    It can be installed by including the file as well:

    <script src="/path/to/vue.js"></script>
    <script src="/path/to/vue-router.js"></script>
    

    After installing it, it is time to tell Vue to use the router. To do so you can do as below:

    import Vue from 'vue';
    import VueRouter from 'vue-router';
    
    Vue.use(VueRouter);
    

    Your components which are bound to routes should be rendered somewhere in your page. This be declared as below:

    <div id="app">
        <div>
            Hello World!
        </div>
        <router-view></router-view>
    </div>
    

    경로 정의

    Each route will have its own unique component bound. You can define your routes as below:

    const routes = [
      { path: '/foo', component: require('./path/to/foo/component') },
      { path: '/bar', component: require('./path/to/bar/component') }
    ];
    
    const router = new VueRouter({
      routes // short for `routes: routes`
    });
    

    If you want yo push the routes to history of user's browser you should activate the history mode as below:

    const router = new VueRouter({
      mode: 'history',
      routes // short for `routes: routes`
    });
    

    And then attach your routes to your view instance:

    const app = new Vue({
      router
    }).$mount('#app');
    

    Note: If you are using the history mode, in order to redirect all your requests to your index.html file so Vue can take care of rest of it you should configure your web server. Unless, by refreshing the browser on a page, it will return 404 since that page actually doesn't exist on the server.

    라우터 링크

    Router links are special since they don't refresh the page but only getting the component that is needed (and push the URL to the history in history mode) so it seems like a new page.

    Instead of a hyper-link ( a tag) you should use router-link as below:

    <router-link to="/foo">Go to foo</router-link>
    

    고급 라우팅



    Vue 라우터는 단순한 몇 가지 경로 이상이며 경로를 처리하는 몇 가지 훌륭한 방법을 제공합니다.

    동적 경로

    Dynamic routes are used to match a series of routes with some params to be acquired.

    A dynamic route is defined just like a normal route but with a colon at the beginning of the dynamic segment(s):

    const routes = [
      { path: '/user/:username', component: require('./path/to/user/component') },
    ];
    

    Now by the route above all of links such as /user/adnanbabakan , /user/dev/ or /user/vue is valid.

    The username can be accessed in the route component as below:

    <div>This is {{ $route.params.username }}'s profile!</a>
    

    Reacting to dynamic routes' param changes

    Considering the example above. If the user moves from /user/adnanbabakan to /user/dev Vue won't destroy the previous instance since it is already going to be the same component rendered again, thus the lifecycle hooks won't be called in order to react to any params changes you can watch the $route object like
    this:

    <script>
      export default {
        watch: {
          $route(to, from) {
    
          }
        }
      };
    </script>
    

    404번 노선

    Every website needs a great 404 route. In a Vue Router we can define an asterisk * route at the end so it catches everything that is not defined.

    Warning: The asterisk route should be defined at the end and after any other route. Unless it will match everything else and ruin your routing system.

    In order to do so look at the code below:

    const routes = [
        // ... Any other routes ...
        { path: '*', component: require('./path/to/404/component') },
    ];
    

    별표 경로

    Asterisks can be used to match another kind of dynamic routes. A dynamic route can only match the dynamic segments between two slashes / but asterisk can do beyond that.

    Look at the route below:

    const routes = [
        { path: '/user-*', component: require('./path/to/user/component') },
    ];
    

    So by the route above routes such as /user-adnan and /user-dev can be rendered.

    By using the route below the $route.params will have a property called pathMatch which will include the part that matched the asterisk.
    For example $route.params.pathMatch in the page /user-adnan will return adnan .

    명명된 경로

    Named routes are used to access long route pattern with their shorter name.

    Imagine you have a pattern like this:

    const routes = [
      {
        path: '/user/profile/setting/',
        component: require('./path/to/user/component')
      }
    ];
    

    You can define a name for it like this:

    const routes = [
      {
        path: '/user/profile/setting/',
        component: require('./path/to/user/component'),
        name: 'settings'
      }
    ];
    

    Now your links can be like this:

    <router-link :to='{name: "settings"}'>
        Profile settings
    </router-link>
    

    Instead of this:

    <router-link to="/user/profile/setting/">
        Profile settings
    </router-link>
    

    Note: When passing an object to to attribute you should bind it.

    매개변수가 있는 명명된 경로

    Some routes might have params as we had some examples above. You can define a name for them as well.

    For example for the route below:

    const routes = [
      {
        path: '/posts/from/:username',
        component: require('./path/to/posts/component'),
      }
    ];
    

    You can have this:

    const routes = [
      {
        path: '/posts/from/:username',
        component: require('./path/to/posts/component'),
        name: 'posts'
      }
    ];
    

    And in order to create a link for this you can have the code below:

    <router-link :to='{name: "posts", params: {username: "adnanbabakan"}}'>
        Profile settings
    </router-link>
    

    프로그래밍 방식 탐색

    As you read before in this cheat sheet you can create a router link using <router-link></router-link> but what if you needed to redirect user programmatically? Well you can do that by this code:

    router.push('/foo');
    

    This code will redirect your user to /foo . This is especially used in a condition or other situations like redirection after login.

    프로그래밍 방식의 명명된 탐색

    You can also use router.push() for named routes like this:

    router.push({name: 'myRoute'});
    

    매개변수를 사용한 프로그래밍 방식 탐색

    As well, router.push() can be used for redirecting with params, like this:

    router.push({name: 'myRoute', params: {paramOne: 'Hello', paramTwo: 'Salam'}});
    

    경로 리디렉션

    Routes can be defined to be redirected to each other. Like this:

    const routes = [
      {
        path: '/foo',
        redirect: '/bar'
      }
    ];
    

    경로 이름 리디렉션

    A route can also be redirected to a named route, like this:

    const routes = [
      {
        path: '/foo',
        redirect: { name: 'myRoute' }
      }
    ];
    

    동적 경로 리디렉션

    A route can be redirected using a function to evaluate the destination, like this:

    const routes = [
      {
        path: '/foo',
        redirect: to => {
          // the function receives the target route as the argument
          // return redirect path/location here.
        }
      }
    ];
    

    매개변수를 사용한 경로 리디렉션

    If the target route has a param it can be passed to the destination as well:

    const routes = [
      {
        path: '/profile/:username',
        redirect: '/user/:username'
      }
    ];
    

    경로 별칭

    A route alias means a route can have multiple addressed to be accessed from.

    For example:

    const routes = [
      {
        path: '/foo',
        alias: '/bar'
      }
    ];
    

    Now the route /foo can be accessed as /bar/ as well.

    A route can have multiple aliases as well:

    const routes = [
      {
        path: '/foo',
        alias: ['/bar', '/baz']
      }
    ];
    

    Check out my free Node.js Essentials E-book here:


    좋은 웹페이지 즐겨찾기