Vue 3 치트 시트

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

우선, 치트 시트에 들어가기 전에 새해의 시작(현재 Shamsi(Jalali) 달력에서 1400년) 및/또는 봄 시즌의 시작을 나타내는 행복한 Nowruz를 기원합니다. 어느 나라에서든 이 행사를 축하하는 사람에게. 새해 복 많이 받으시고 행복한 Nowruz. 내가 이 글을 쓰고 있는 지금은 새해가 5일 지난 Farvardin, 1400의 5일입니다 :).

아시다시피 야심찬 Vue 개발자라면 얼마 전에 Vue가 버전 3을 출시했습니다. 이 버전에는 몇 가지 주요 변경 사항과 일부 사소한 변경 사항이 있습니다. 여기에서 치트 시트로 나열하고 있으므로 언제든지 XD 내 게시물을 참조할 수 있는 것처럼 원할 때마다 사용할 수 있습니다. 일부 기능은 더 많은 설명이 필요하기 때문에 이 게시물은 치트 시트에 불과합니다.

일부 코드 예제는 Vue's official documentation 에서 가져온 것입니다.

저는 Vue 3가 Vue를 이전보다 대규모 엔터프라이즈 애플리케이션 개발을 위한 훨씬 더 나은 솔루션으로 만드는 데 큰 진전을 이루었다고 믿습니다.

내용의 테이블


  • New way to create
  • Configuration scope

  • Composition API
  • ref

  • Fragments
  • Teleport

  • 만드는 새로운 방법

    Previously, what we used to do was to instantiate a new Vue instance, and mount it in an element (usually being the #app ) as below:

    import Vue from 'vue'
    import App from './App.vue'
    
    new Vue({
        render: h => h(App)
    }).$mount('#app')
    

    Now what we have to do is to call the createApp method from 'vue' to create a new app and then mount it in an element:

    import { createApp } from 'vue'
    import App from './App.vue'
    
    const app = createApp(App)
    
    app.mount('#app')
    

    구성 범위

    In Vue 3, instead of configuring the Vue global object directly, for adding plugins and etc, you can configure your object instance instead.

    Previously:

    import Vue from 'vue'
    import App from './App.vue'
    
    Vue.use(YOUR_PLUGIN)
    
    new Vue({
        render: h => h(App)
    }).$mount('#app')
    

    New way:

    import { createApp } from 'vue'
    import App from './App.vue'
    
    const app = createApp(App)
    
    app.use(YOUR_PLUGIN)
    
    app.mount('#app')
    

    구성 API

    As much as it sounds really dangerous when you read this feature's name, it is a super simple and very useful feature. This feature lets you split your component into smaller pieces, simply put. This allows you to use repeatable parts of your components without needing to code them again.

    Given that you have to components, named Fruits and Countries and in them, you have a list and an input to search in the list to see if the user's input exists or not.

    This is a very simple example so you don't get frustrated :D.

    The search function uses a very simple linear search algorithm. Given that you can share this function over components using the setup method in Vue 3. Everything that the setup method returns are available in your component.

    Here is an example:

    For Fruits :

    <template>
      <div>
        <label>
          Search in fruits:
          <input type="text" v-model="userInput"/>
        </label>
        <button @click="search">Search</button>
      </div>
    </template>
    
    <script>
    import {ref} from 'vue'
    import { search as searchFunction } from '@/compositions/search-function'
    
    export default {
      setup() {
        let list = ref(['apple', 'orange', 'banana', 'mango', 'pineapple'])
        let userInput = ref(null)
    
        const search = () => {
          searchFunction(userInput, list)
        }
    
        return {
          list,
          userInput,
          search
        }
      }
    }
    </script>
    

    And for Countries :

    <template>
      <div>
        <label>
          Search in countries:
          <input type="text" v-model="userInput"/>
        </label>
        <button @click="search">Search</button>
      </div>
    </template>
    
    <script>
    import {ref} from 'vue'
    import {search as searchFunction} from "@/compositions/search-function";
    
    export default {
      setup() {
        let list = ref(['Iran', 'Spain', 'Turkey', 'US', 'China', 'France'])
        let userInput = ref(null)
    
        const search = () => {
          searchFunction(userInput, list)
        }
    
        return {
          list,
          userInput,
          search
        }
      }
    }
    </script>
    

    As you can see we imported a simple function called search as searchFunction so it doesn't conflict with the search function we use in the template (although it doesn't matter since Vue will call from its own methods, better safe than sorry XD).

    심판

    You can make every variable reactive using the ref method imported from vue . If you have a React background, this acts similar to useState in React. Using this method you can create a reactive variable and return it in your setup method. The argument that the ref method receives is the default value (initial value).

    import {ref} from 'vue'
    
    export default {
      setup() {
        let name = ref('Adnan')
    
        return {
          name
        }
      }
    }
    
    If you are still confused about the Composition API, feel free to check Vue's official documentation about Composition API , 가장 좋은 설명을 제공합니다.

    파편

    Fragments let you return multiple root nodes (elements) from your components without needing to wrapping them inside another element such as a div . This way you won't have redundant elements in your DOM.

    Here is a simple component called Boxes.vue :

    <template>
      <div id="box-one" />
      <div id="box-two" />
    </template>
    
    <script>
    export default {
    
    }
    </script>
    
    <style lang="scss" scoped>
    #box-one {
      background: red;
      width: 100px;
      height: 100px;
    }
    
    #box-two {
     background: blue;
      width: 150px;
      height: 150px;
    }
    </style>
    

    텔레포트

    Teleport lets you teleport your elements (Duh!). This means although semantically your element might reside inside another element it is possible to move it inside another one. Like your page's body. This is super helpful in scenarios such as a modal.

    Here is sample:

    <template>
      <teleport to="body">
        <div class="modal" v-if="isModalActive">
          Boom! I teleported!
        </div>
      </teleport>
      <button @click="isModalActive = !isModalActive">{{ isModalActive ? 'Close' : 'Open' }} modal</button>
    </template>
    
    <script>
    export default {
      data() {
        return {
          isModalActive: false
        }
      }
    }
    </script>
    
    <style scoped>
    .modal {
      background: #aaaaaa;
      padding: 10px;
      border-radius: 7px;
      position: absolute;
      top: 10px;
      right: 10px;
    }
    </style>
    

    As you can see in the code sandbox since the element that our component is in has a relative position it means that if an absolute element is set inside it, the mentioned element will be bound inside it. Using the teleport feature we've moved our .modal so its parent would be the body. This way it will still be controlled by the component it is defined in but the placement in the DOM will be different.

    It is possible to use a # to determine an id of an element as a destination as below:

    <template>
      <teleport to="#where-your-want">
        <div class="modal" v-if="isModalActive">
          Boom! I teleported!
        </div>
      </teleport>
      <button @click="isModalActive = !isModalActive">{{ isModalActive ? 'Close' : 'Open' }} modal</button>
    </template>
    

    These were the most drastic things you've wanted to learn about Vue 3. I hope you enjoyed it!

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


    좋은 웹페이지 즐겨찾기