programing

Vue 2에서 비반응 구성 요소 데이터를 설정하는 방법

prostudy 2022. 7. 21. 23:55
반응형

Vue 2에서 비반응 구성 요소 데이터를 설정하는 방법

카테고리 배열이 있습니다.이 배열은 (생성된 후크에) 한 번 로드된 후 항상 정적입니다.구성 요소 템플릿에서 이 배열 값을 렌더링합니다.

<template>
    <ul>
        <li v-for="item in myArray">{{ item }}</li>
    </ul>
</template>

데이터 속성 모양(myArray 미포함 - 사후 대응 바인딩 필요 없음):

data() {
    return {
        someReactiveData: [1, 2, 3]
    };
}

내 생성 후크:

created() {
    // ...
    this.myArray = ["value 1", "value 2"];
    // ...
}

문제는 Vue throw 오류 - 템플릿에서 myArray를 사용할 수 없다는 것입니다. 이 변수는 DOM 생성 시 생성되지 않기 때문입니다.마운트됩니다.

그럼 어떻게 하는 거죠?또는 성분 상수를 어디에 저장할 수 있습니까?

Vue는 의 모든 속성을 설정합니다.data세터/게터 옵션을 선택하여 반응시킵니다.자세한 반응성 참조

네가 원하니까myArray스태틱하게 하려면 이 옵션을 커스텀옵션으로 생성하여

export default{
    data() {
        return{
            someReactiveData: [1, 2, 3]
        }
    },
    //custom option name myArray
    myArray: null,
    created() {
        //access the custom option using $options
        this.$options.myArray = ["value 1", "value 2"];
    }
}

템플릿의 이 커스텀옵션을 다음과 같이 반복할 수 있습니다.

<template>
    <ul>
        <li v-for="item in $options.myArray">{{ item }}</li>
    </ul>
</template>

여기 바이올린이 있습니다.

사실, 속성 설정thiscreated()즉시 사용할 수 있습니다.

<template>
  <div id="app">
    <ul>
      <li v-for="item in myArray" :key="item">
        {{ item }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  name: "app",
  created() {
    this.myArray = [
      'item 1',
      'item 2'
    ];
  }
};
</script>

렌더링하다

<div id="app">
  <ul>
    <li>
      item 1
    </li>
    <li>
      item 2
    </li>
  </ul>
</div>

데모 사이트: 。

다음과 같은 정적 데이터(반응하지 않음)를 사용하는 것이 좋습니다.

믹스인을 만듭니다(이름 지정).static_data.js)의 내용은 다음과 같습니다.

import Vue from 'vue'

Vue.prototype.$static = {}

export default {
  beforeCreate () {
    const vue_static = this.$options.static
    const vue_static_destination = this.$static || this

    if (vue_static && typeof(vue_static) === 'function') {
      Object.assign(vue_static_destination, vue_static.apply(this))
    } else if (vue_static && typeof(vue_static) === 'object') {
      Object.assign(vue_static_destination, vue_static)
    }      
  }
}

정적 데이터를 사용하는 컴포넌트에서 다음을 수행할 수 있습니다.

import use_static_data from '@mixins/static_data'

export default {
  mixins: [use_static_data],

  static: () => ({
    static_value: 'Vue is awesome'
  }),

  created () {
    console.log(this.$static.static_value); // Vue is awesome
  }
}

vue-static 패키지도 있습니다.

크레딧은 이쪽입니다.

보관하고 싶다면data적절한 방법은 오브젝트를 사용하는 것입니다.매뉴얼에 기재되어 있는 freeze discloss:

유일한 예외는 오브젝트를 사용하는 것입니다.freeze(프리즈)는 기존 특성이 변경되는 것을 방지합니다. 즉, 반응도 시스템은 변경을 추적할 수 없습니다.

이 코드 줄을 사용해 보세요.개체를 복사하여 반응성을 제거할 수 있습니다.

var newObj = JSON.parse(JSON.stringify(obj));

언급URL : https://stackoverflow.com/questions/45814507/how-to-set-a-component-non-reactive-data-in-vue-2

반응형