현재 vue 구성 요소의 메서드를 기본 프로펠러 값으로 사용
Vue 컴포넌트에 속성으로 기능을 전달합니다.Let it be 함수를 호출해야 합니다.@click하지만 어떤 이유로든 컴포넌트의 기본 동작을 유지하고 싶습니다.디폴트 동작은 원하는 만큼 쉽지 않기 때문에method디폴트 기능으로 사용합니다.기본 동작에는 구성요소 상태(프로포즈, 데이터, 기타 메서드 등)의 데이터가 필요하기 때문입니다.
방법이 있을까요?
예시를 첨부했습니다.예상되는 동작:
단추works fine경계태세를 갖추다You are welcome!
단추nope경계태세를 갖추다You are welcome as well!아무것도 안 해
Vue.component('welcome-component', {
template: '#welcome-component',
props: {
name: {
type: String,
required: true,
},
action: {
type: Function,
required: false,
default: () => { this.innerMethod() },
},
},
methods: {
innerMethod() {
alert("You are welcome as well!");
}
}
});
var app = new Vue({
el: "#app",
methods: {
externalMethod() {
alert("You are welcome!");
}
}
});
#app {
margin: 20px;
}
.holder > button {
margin: 10px;
padding: 5px;
font-size: 1.1em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<welcome-component name="works fine" :action="externalMethod"></welcome-component>
<welcome-component name="nope"></welcome-component>
</div>
<script id='welcome-component' type='x-template'>
<div class="holder">
<button @click="action">{{ name }}</button>
</div>
</script>
vue 문서에서:
"Note that props are validated before a component instance is created, so instance properties (e.g. data, computed, etc) will not be available inside default or validator functions."(https://vuejs.org/v2/guide/components-props.html)
참조innerMethod따라서 컴포넌트 기능을 아직 사용할 수 없는 경우 중 하나입니다.
아이디어: 이러한 기능을 갖추는 것이 중요한 경우, 나중에 라이프 사이클 훅(작성, 마운트 등)에서 타입을 확인할 수 있습니다.action이function함수가 아닌 경우(프로포트를 통해 전달되지 않음을 의미), innerMethod를 수동으로 할당합니다.
이 방법은 효과가 있지만 스패너의 총량입니다.
action: {
required: false,
default () {
return () => this.innerMethod();
},
},
이 모든 것을 없애야 했습니다.type: Function. 보통.default는 적절한 기본값을 반환하기 위해 호출되는 함수입니다.단, 만약 소품이type: Function이 기능은 기본 기능으로 간주됩니다.이 경우 문제가 됩니다. 왜냐하면 우리는 이 모든 것을 잃기 때문입니다.this바인드
내부 화살표 기능은 이 방법을 사용할 수 없는 문제를 회피하기 위해 필요합니다.default함수가 호출됩니다.
가능하다면, 이 제품의 사용을 포기하는 것이 좋습니다.default호출이 필요할 때 '기본값'을 적용하기만 하면 됩니다.그래서 전화하는 것보다action직접 에click핸들러 대신 콜하는 메서드invokeAction다음과 같이 보입니다.
invokeAction () {
if (this.action) {
this.action();
} else {
this.innerMethod();
}
}
언급URL : https://stackoverflow.com/questions/57313153/use-current-vue-components-method-as-default-prop-value
'programing' 카테고리의 다른 글
| Java에서의 RESTful 콜 (0) | 2022.08.07 |
|---|---|
| C#에서 C 함수를 호출할 수 있습니까?그물 (0) | 2022.08.07 |
| VueJS 싱글 파일 컴포넌트(타이프 스크립트 포함):모듈 정보를 찾을 수 없습니다.표시하다 (0) | 2022.08.07 |
| VueJ가 계산한 속성이 HTML 코드를 반환하는 경우 어떻게 처리합니까? (0) | 2022.08.07 |
| Vuex: 작업이 완료될 때까지 기다리는 방법 (0) | 2022.08.07 |