programing

VueJS 구문: 마운트에서 실행 중인 메서드

prostudy 2022. 7. 18. 22:05
반응형

VueJS 구문: 마운트에서 실행 중인 메서드

데이터를 로드하고 싶습니다.vue-resource페이지가 로드되면 새로 고침 버튼을 누르면 해당 데이터를 다시 로드합니다.

코드를 건조하게 유지하기 위해 이 기능을 메서드에 넣고 싶었습니다.이것이 나의 첫 번째 시도였다.

index.syslog:

<div id="app"></div>

app.filename:

const Vue = window.Vue = require("vue");
require("vue-resource");
const App = require("./components/App.vue");

window.app = new Vue({
    el: "#app",
    render: h => h(App)
});

컴포넌트/app.vue:

<template>
    <div>
        <h1>Test</h1>
        <p>{text}</p>
        <button @click="loadData">Reload</button>
    </div>
</template>
<script>
export default {
    // This fails
    mounted: this.loadData,
    methods: {
        loadData() {
            // This syntax may be wrong, too. But the function isn't
            // even running, so I haven't started to debug this yet
            this.$http.get("https://icanhazip.com")
                .then(xhr => this.text = xhr.body);
        }
    }
};
</script>

그러면 10행의 에러가 발생합니다.components/app.vue:

    mounted: this.loadData,

말하다Uncaught TypeError: Cannot read property 'reloadData' of undefined

어떻게 하면mounted에 정의되어 있는 임의의 메서드를 참조하는 기능methods?

를 사용해 주세요.mounted올바른 메서드 선언과 함께 다음과 같은 방식으로 이벤트를 발생시킵니다.

export default {        
    mounted() {
      this.loadData();
    },
    methods: {
        loadData() {
            // This syntax may be wrong, too. But the function isn't
            // even running, so I haven't started to debug this yet
            this.$http.get("https://icanhazip.com")
                .then(xhr => this.text = xhr.body);
        }
    }
};

자세한 내용은 여기를 참조하십시오.
https://vuejs.org/v2/api/#마운트

클릭과 같은 DOM 이벤트를 듣고 다음과 같은 방법으로 일부 기능을 실행하려면 v-on(@) 명령을 사용해야 합니다.

<button @click="loadData">Reload</button>

@Thusitha가 마운트 대상입니다.업데이트가 필요합니다.

언급URL : https://stackoverflow.com/questions/46427612/vuejs-syntax-running-method-on-mount

반응형