it-source

Vue에서 변수를 선언하는 것과 다른 점은 무엇입니까?

criticalcode 2022. 11. 29. 21:41
반응형

Vue에서 변수를 선언하는 것과 다른 점은 무엇입니까?

변수를 선언하는 것의 차이를 다른 방법으로 설명해 주시겠습니까?언제 이런 식으로 신고해야 하나요?

<script>
const someVariable = 12345

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

export default {
  name: 'App',
  data() {
    return {
      someVariable: 12345
    }
  }
}
</script>

첫 번째 버전에서는someVariable템플릿 내

<script>
const someVariable = 12345

export default {
  name: 'App',
}
</script>
<template> <p> {{someVariable}} </p> </template> //doesn't work

Vue3에서 사용 가능:

동작시키기 위해서, 1개의 커맨드를 추가할 수 있습니다.setup키워드는 스크립트에 포함되지만 변수 값은 로 묶어야 합니다.ref(...)또는reactive(...)변경에 대응하고 싶은 경우 추가 정보

<script setup>
const someVariable = 12345

export default {
  name: 'App',
}
</script>
<template> <p> {{someVariable}} </p> </template> //works (you can see the data)

일반적인 싱글 파일 컴포넌트는 다음과 같습니다.

<template>
...
</template>

<script>
...
</script>
  1. 외부 변수를 정의하는 경우export스테이트먼트는 스크립트태그 내부의 어느 곳에서나 사용할 수 있는 단순한 javascript 변수입니다.구성 요소에 바인딩되거나 Vue와 어떤 방식으로도 관련되지 않습니다.장점:
    • 변수가 전체에 존재합니다.<script>요소의 범위.
    • 구속력이 없는 내부 기능 안에서 사용할 수 있습니다.this.
  2. 데이터 함수 내부에서 변수를 정의하거나 정확하게 표현하려면 구성 요소 인스턴스의 데이터 객체에 대한 속성을 정의해야 합니다. 그러면 구성 요소가 구성 요소에 바인딩되므로 데이터 함수 내부에서 사용할 수 있습니다.<template>태그. 장점:
    • 변수는 다음 위치에서 참조할 수 있습니다.<template>
    • Vue의 반응성을 활용할 수 있습니다.이 변수에 계산된 속성을 정의할 수 있습니다.템플릿에서 사용하면 html이 갱신되어 이 변수의 변경이 반영됩니다.
    • 아이 컴포넌트에 소품으로 전달할 수 있습니다.
    • Vue devtools를 사용하여 쉽게 디버깅할 수 있으며 변수의 변경 사항을 확인할 수 있습니다.변수를 다음과 같이 콘솔에 로그인할 수도 있습니다.$vm.data.someVarDataVue 컴포넌트의 인스턴스에 변수가 추가됩니다.
<template>
    <div>
        <div :class="someVarData"/> <!-- This is Ok -->
        <div :class="someVar"/> <!-- This is not Ok -->
    </div>
<template>
<script>
const someVar = "blah";
export default {
    data() {
        return {
            someVarData: "blahData",
        };
    },
    mounted() {
        const el = document.getElementById('myId');
        el.addEventListener('mouseenter', function () {
            console.log(someVar); // This is Ok
            console.log(this.someVarData); // This is not Ok
        });
    },
    beforeRouteEnter() { // <--- Vue-router's Navigation guard
        console.log(someVar); // This is Ok
        console.log(this.someVarData); // This is not Ok
    },
</script>

따라서 내보내기 외부에 변수를 정의하면 코드 흐름을 이해하기 어려워지므로 이러한 변수를 정의하지 마십시오.수출 이외의 변수를 사용하지 않도록 접근 방식을 재설계할 수 있는 방법은 거의 항상 있습니다.

예를 들어, 위의 예에서 데이터 변수를 계속 사용할 수 있습니다.mounted후크 및 내비게이션가드에는 몇 가지 변경이 있습니다.

    mounted() {
        const el = document.getElementById('myId');
        el.addEventListener('mouseenter', () => {
            console.log(someVar); // This is Ok
            console.log(this.someVarData); // Ok - works because we change the function to arrow function, so it is bound to the instance's `this`
        });
        el.addEventListener('mouseenter', function () {
            console.log(someVar); // This is Ok
            console.log(this.someVarData); // Ok - works because we have manually bound the function to the instance's `this`
        }.bind(this));
    },
    beforeRouteEnter(to, from, next) { // <--- Vue-router's Navigation guard
        console.log(someVar); // This is Ok
        console.log(this.someVarData); // This is not Ok
        next((vm) => {
            console.log(vm.someVarData); // Ok - Navigation guard's next function provides the instance's context as a callback parameter
        });
    },

언급URL : https://stackoverflow.com/questions/69301906/what-is-the-difference-between-declaring-variables-in-vue

반응형