뷰 치트 시트 1

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

Vue.js를 좋아하고 즐겨 쓰기 때문에 이 게시물에서는 Vue.js의 거의 모든 기본 개념(공식 웹사이트 기반)을 다루고 목차를 두어 원하는 섹션에 더 쉽게 액세스할 수 있도록 하겠습니다. .

이 부분은 구성 요소를 다루지 않습니다.

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

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


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



마사 유



Software Developer working mainly with Python, Javascript



내용의 테이블



  • Interpolations
  • Simple interpolation

  • Interpolation with expression
  • Simple expression interpolation
  • Ternary operator expression interpolation

  • Raw HTML interpolation


  • Binding
  • Simple binding
  • Binding with concat
  • Conditional binding

  • Two-way data binding
  • Events

  • Dynamic arguments
  • Dynamic arguments by object

  • Computed properties
  • Watchers

  • Conditional render
  • Toggle display conditional rendering


  • List rendering
  • Array rendering
  • Object rendering
  • Iterate in range


  • 보간

    Interpolation means putting or rendering your data which is possible very easily using Vue's double-mustache syntax.

    단순 보간

    By using double-mustache syntax you can render your data:

    <span>My name is: {{ myName }}</span>
    

    표현식을 사용한 보간

    Interpolations can contain simple expressions in Vue.

    단순 표현식 보간

    You can also use JavaScript expressions inside double-mustaches:

    <span>I'm {{ myAge + 5 }} years old!</span>
    

    You can also use methods to manipulate your data and return an string or integer to be rendered:

    <span>My pets' names are {{ myPets.join(", ") }}</span>
    

    삼항 연산자 표현식 보간

    You can also use ternary operator to have a simple conditional rendering:

    <span>I'm a {{ myAge > 50 ? 'kinda old' : 'young' }}!</span>
    

    Note:

    • You can only use one expression inside double-mustaches
    • An expression is different than a statement. For example the code below won't work because it is not and expression, but a statement:
    <!--THIS IS WRONG-->
    {{ let msg = 'Hello World!'; }}
    
    • Flow control is not supported in double-mustaches:
    <!--THIS IS WRONG-->
    {{ if(true) { return 'Yes!' } }}
    

    원시 HTML 보간

    If you don't want to escape your data and render it as real HTML use the v-html directive:

    <span v-html="myHTMLData"></span>
    

    Warning: Rendering HTML can be risky since it can cause into XSS attacks on your website.

    제본

    Binding means using your data inside your tag's attributes.

    단순 바인딩

    Something wrong that new Vue developers try to do is putting a data into a attribute like this:

    <span class="{{ myClass }}"></span>
    

    But this is wrong and you actually have to bind it:

    <span v-bind:class="myClass"></span>
    

    There is a shorter way of binding which is by omitting v-bind directive, like below:

    <span :class="myClass"></span>
    

    concat으로 바인딩

    So what if you want to combine some string with your data when binding? Well use put your string inside of quotes and concat it as usual:

    <span :class="myClass + 'test'"></span>
    

    This can really be useful by using it inside hyperlinks:

    <a :href="baseURL + '/post/' + postId">Read more</a>
    

    The example above is a good example of a link to the post including the base URL and the post suffix and then the post id.

    조건부 바인딩

    You can use bindings to conditionally do something.

    For the attributes which don't have a value like disabled or required if your bound data return true the attribute will be added and if returns false the attribute won't be added to the element.

    <button :disabled="true"></button>
    

    You can also use expressions which return boolean:

    <button :disabled="password.length < 6"></button>
    

    You can use an object inside the class attribute in order to bind the specified class if the condition is met:

    <div :class="{green: true, red: false}"></div>
    

    In the example above green class will be added to our div but not red.
    You can use comparison and logical operators as well:

    <div :class="{green: 5 > 1, red: false && 9 < 16}"></div>
    

    양방향 데이터 바인딩

    By using the v-model directive you can create a two-way data binding. Which means the user can change the data using an input and see the result simultaneously if needed.

    <input v-model="message" placeholder="edit me">
    <p>Message is: {{ message }}</p>
    
    let app = new Vue({
        el: '#app',
        data: {
            message: ''
        }
    });
    

    The v-model directive can work on almost every input type.

    이벤트

    Events are called when a specific action is performed on an element.
    Events are declared with v-on directive.

    <div id="app">
        <button v-on:click="callMyfunction"></button>
    </div>
    
    let app = new Vue({
        el: '#app',
        methods: {
            callMyfunction() {
                alert('This is it!');
            }
        }
    });
    

    When a click is performed on this button it will call the callMyFunction method.

    You can use anonymous functions as well:

    <button v-on:click="() => alert('Hello my friend')"></button>
    

    There is shorthand for events as well:

    <button @click="() => alert('Hello my friend')"></button>
    

    동적 인수

    Imagine when you want to have an attributes name evaluated. Well this is possible by doing like below:

    <div v-bind:[myAttribute]="myData"></div>
    

    You can also have an event's name dynamically attached:

    <div v-on:[myEvent]="doSomething"></div>
    

    개체별 동적 인수

    There is also a way of binding dynamic arguments by using an object and JavaScript's native dynamic key syntax, like below:

    <button v-on="{[myAttr]: true}">Click on me if you can</button>
    
    let app = new Vue({
        el: '#app',
        data: {
            myAttr: 'disabled'
        }
    });
    

    This can be used on events as well:

    <button v-on="{[myEvent]: function() { alert("Hello world!") }}">Hi</button>
    
    let app = new Vue({
        el: '#app',
        data: {
            myEvent: 'click'
        }
    });
    

    계산된 속성

    Computed properties are a way of cleaning your code and use them instead of expressions inside of your double-mustaches or other places.

    Imagine you have the code below:

    <p>
    The best programming languages are: {{ programmingLanguages }}<br>
    But the worst are: {{ programmingLanguages.split(', ').reverse().join(', ') }}
    </p>
    

    Instead you can define a computed property like below and use it instead of worst programming languages:

    <p>
    The best programming languages are: {{ programmingLanguages }}<br>
    But the worst are: {{ worstProgrammingLanguages }}
    </p>
    
    let app = new Vue({
        el: '#app',
        data: {
            programmingLangauges: 'JavaScript, C#, PHP, Python, LALALA, HOHOHO'
        }
        computed: {
            worstProgrammingLanguages() {
                return this.programmingLangauges.split(', ').reverse().join(', ');
            }
        }
    });
    

    The order is not real and I'm not judging any programming language. It is just for demonstration.

    Computed properties are getters which means they only return something and have no role in setting the data.

    You can change this behaviour and set both set and get methods for a data, like below:

    let app = new Vue({
        el: '#app',
        data: {
            myFirstName: 'Adnan',
            myLastName: 'Babakan'
        }
        computed: {
            myFullName: {
                get(): {
                    return this.myFirstName + ' ' + this.myLastName;
                },
                set(v): {
                    let parts = v.split(' ');
                    this.myFirstName = parts[0];
                    this.myLastName = parts[1];
                }
            }
        }
    });
    

    The code above will split the string by space and set the first part as first name and the second part as the last name when you are trying to set a data to myFullName but when getting the data it will concat first name and last name.

    감시자

    A more generic way of knowing when a data changes is by using watchers.

    let app = new Vue({
        el: '#app',
        data: {
            myAge: 19
        }
        watch: {
            myAge(v) {
                console.log('I\'m now ' + v);
            }
        }
    });
    

    Note: Watchers don't manipulate data unless you want.

    조건부 렌더링

    A conditional rendering is used when you want to display parts of your UI according to some condition(s).

    <span v-if="isUserLoggedIn">Hello user</span>
    <span v-else>Hi guest!</span>
    

    Your conditions can have an 'else-if' as well:

    <span v-if="favoriteColor === 'red'">Red like apple</span>
    <span v-if="favoriteColor === 'blue'>Blue like sky</span>
    <span v-else>Hmmm....</span>
    

    Vue is smart and will only replace the parts that are different.
    For example if you have a an input for logging in by email or username switching between two parts by condition won't erase and re-render that input and user's inputted value won't be deleted:

    <template v-if="loginType === 'username'">
      <label>Username</label>
      <input placeholder="Enter your username">
    </template>
    <template v-else>
      <label>Email</label>
      <input placeholder="Enter your email address">
    </template>
    

    Though, by using key you can tell Vue that these fields are completely different and you should re-render them:

    <template v-if="loginType === 'username'">
      <label>Username</label>
      <input placeholder="Enter your username" key="username-input">
    </template>
    <template v-else>
      <label>Email</label>
      <input placeholder="Enter your email address" key="email-input">
    </template>
    

    디스플레이 조건부 렌더링 전환


    v-show을 사용하면 다음과 같이 요소를 렌더링하지만 숨깁니다(display 속성을 none로 설정).

    <span v-show="true">Hello there!</span>
    

    참고: v-show<template> 요소를 지원하지 않으며 v-else에서도 작동하지 않습니다.

    참고: v-if은 초기에 false 조건이 있는 블록이 렌더링되지 않음을 의미하는 지연입니다. 반면에 v-show은 실제로 블록을 렌더링하지만 숨깁니다.

    목록 렌더링

    Rendering a list of data is almost like looping in other programming languages.

    배열 렌더링

    Often it happens you want to iterate around an array and render them.
    This is possible by using v-for directive:

    <ul id="example-1">
      <li v-for="item in items">
        {{ item.message }}
      </li>
    </ul>
    
    var example1 = new Vue({
      el: '#example-1',
      data: {
        items: [
          { message: 'Foo' },
          { message: 'Bar' }
        ]
      }
    });
    

    You can also pass a second argument to access the index of current item:

    <ul id="example-2">
      <li v-for="(item, index) in items">
        {{ index }} - {{ item.message }}
      </li>
    </ul>
    
    var example2 = new Vue({
      el: '#example-2',
      data: {
        items: [
          { message: 'Foo' },
          { message: 'Bar' }
        ]
      }
    });
    

    개체 렌더링

    Object rendering is no harder than array rendering:

    <ul id="v-for-object" class="demo">
      <li v-for="value in object">
        {{ value }}
      </li>
    </ul>
    
    new Vue({
      el: '#v-for-object',
      data: {
        object: {
          title: 'How to do lists in Vue',
          author: 'Jane Doe',
          publishedAt: '2016-04-10'
        }
      }
    });
    

    You can also have access to the name of the property using the second argument:

    <ul id="v-for-object" class="demo">
      <div v-for="(value, name) in object">
        {{ name }}: {{ value }}
      </div>
    </ul>
    
    new Vue({
      el: '#v-for-object',
      data: {
        object: {
          title: 'How to do lists in Vue',
          author: 'Jane Doe',
          publishedAt: '2016-04-10'
        }
      }
    });
    

    Accessing to the index is also available when iterating around an object:

    <ul id="v-for-object" class="demo">
      <div v-for="(value, name, index) in object">
        {{ index }}. {{ name }}: {{ value }}
      </div>
    </ul>
    
    new Vue({
      el: '#v-for-object',
      data: {
        object: {
          title: 'How to do lists in Vue',
          author: 'Jane Doe',
          publishedAt: '2016-04-10'
        }
      }
    });
    
    6

    범위에서 반복

    Iterating in a range of numbers is also pretty easy:

    <div>
      <span v-for="n in 10">{{ n }} </span>
    </div>
    

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


    좋은 웹페이지 즐겨찾기