programing

VueJS: 렌더 함수에서 계산된 값에 액세스하는 방법

bestcode 2022. 9. 5. 23:01
반응형

VueJS: 렌더 함수에서 계산된 값에 액세스하는 방법

현재 다음 렌더링 기능을 가진 컴포넌트가 있습니다.

render(createElement, context) {

        return createElement(
            'div', {
                'class': 'sliced'
            },
            [
                createElement('div', {
                        'class' : 'sliced-inner',
                        'style' : context.style
                    }
                )

            ]
        )

    },

기능을 추가했습니다: true."style"은 계산된 값이지만 컨텍스트 개체와 함께 전달되지 않는 것 같습니다.Vue 렌더 함수에서 계산된 값에 액세스할 수 있는 방법이 있습니까?

기능 컴포넌트에는 상태가 없기 때문에 계산된 속성은 장황합니다.다음 예제에서는 헤더 컴포넌트를 만듭니다.foo그리고.bar클릭하면:

Vue.component('message', {
  render (createElement) {
    return createElement('h1', {
      on: {
        click: event => {
          return this.foo = !this.foo 
        }
      }
    }, this.fooBar)
  },
  computed: {
    fooBar() {
      return (this.foo) ? 'foo' : 'bar'
    }
  },
  data(){
    return {
      foo: true
    }
  }
});

보시는 바와 같이 헤더 값은 계산에 근거하고 있으며 기능 컴포넌트가 아니기 때문에 정상적으로 동작합니다.https://jsfiddle.net/hwbbukvd/

이 컴포넌트를 기능 컴포넌트로 하면functional: truehttps://jsfiddle.net/cygjdjru/ 의 컴포넌트에 의존하기 때문에 동작하지 않습니다.

참조: https://vuejs.org/v2/guide/render-function.html#Functional-Components

당신의 경우, 리액티브한 스타일을 찾고 있지 않다면 소품 하나를 건네고 싶을 겁니다.

Vue.component('message', {
  functional: true,
  render(createElement, context) {
    return createElement('h1', context.props.foo)
  },
  props: {
    foo: {
      required: true
    }
  }
});

참조: https://jsfiddle.net/qhzh0a2c/

언급URL : https://stackoverflow.com/questions/46910101/vuejs-how-to-access-computed-values-in-render-function

반응형