首页 > 解决方案 > Vue.js (v.2) 仅在单击按钮后加载(获取)数据

问题描述

我是 VUE 的初学者,我编写了代码,在加载网页后,从 json 下载数据并使用 id “app” 渲染它。

但是,我需要的数据不是在开始时加载,而是在单击按钮后才加载。

非常感谢您的提示和建议。

const app = new Vue ({
    el: '#app',
    data: {
        urlPrefix: '',
        newName: '',
        newDescription: '',
        newExperts_advice: '',
        newProduct_benefit_2: '',
        newImage: '',
        characters: [{
                
            }
        ],
    },
    methods: {
        add() {
                this.characters.push ({
                    name: this.newName, 
                    description: this.newDescription, 
                    experts_advice: this.newExperts_advice,
                    product_benefit_2: this.newProduct_benefit_2,
                    image: this.newImage,
                })
        }
    },
    created: function(){
        fetch('./data.json')
        .then(res => res.json())
        .then(json => this.characters = json) 
    }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>TEST</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.js"></script>
    <link rel="icon" href="favicon.ico" type="image/x-icon"/>
</head>
<body>
    <div id="app">
        <button>Fetch data</button>
        <div class="info-v1" v-for="item in characters">
            <section class="head">
                <h2>{{ item.name }}</h2>
                    <p> {{ item.description }}</p>
            </section>
            <section class="body">
                <img v-bind:src="urlPrefix +  item.image " /> 
                <h3>{{ item.product_benefit_2 }}</h3>
                <p>{{ item.experts_advice }}</p>
            </section>
        </div>
    </div>
  </body>
</html>

标签: vuejs2

解决方案


首先,您应该在获取数据的方法中创建方法。

methods: {
  yourNewMethodToFetchData() {
    fetch('./data.json')
    .then(res => res.json())
    .then(json => this.characters = json) 
  }
}

第二次将点击事件添加到您的获取数据按钮,如下所示:

<button @click="yourNewMethodToFetchData">Fetch data</button>

created最后从钩子中删除获取代码:

created: function(){
    
}

推荐阅读