【问题标题】:Changing a button to say "Loading" with a loading animation on click将按钮更改为“正在加载”,单击时带有加载动画
【发布时间】:2019-11-19 06:01:07
【问题描述】:

我创建了一个 Vue 按钮,当单击并加载更多内容时,它会显示“加载更多”,然后显示“正在加载...”。但是,我现在想在“正在加载”旁边添加另一个组件作为加载动画。该按钮完全可以正常工作,但我只想在“加载”一词旁边添加该动画。

我曾尝试使用 Vue 的 ref 标签,但在我的方法中成功使用它的运气并不好。

Loader.vue:

<template>
  <div
    ref="sdcVueLoader"
    class="sdc-vue-Loader"
  >
    Loading...
  </div>
</template>

<script>
export default {
  name: 'Loader'
</script>

App.vue:

<Button
  :disabled="clicked"
  @click="loadMore"
>
  {{ loadMoreText }}
</Button>

<script>
import Button from './components/Button'
import Loader from './components/Loader'

export default {
  name: 'ParentApp',
  components: {
    Button,
    Loader
  },
  data () {
    return {
      loadMoreText: 'Load More',
      clicked: false
    }
  },
  methods: {
    loadMore () {
      if ... {
        this.page += 1
        this.loadMoreText = 'Loading...' + this.$refs.sdcVueLoader
        this.clicked = true
        this.somerequest().then(resp => {
          this.clicked = false
          this.loadMoreText = 'Load More'
        })
        return this.loadMoreText
      }
    }
</script>

我希望按钮能够像现在一样继续工作,但现在当在 app.vue loadMore 方法中单击按钮时,“Loader”组件也会显示在“正在加载...”旁边。

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component vue-cli


    【解决方案1】:

    如果你想在 html 中做任何复杂的事情,最好把它移到你的模板中。在您的情况下,您有两种状态:正在加载或未加载。因此,让我们创建一个变量loading,它可以是truefalse

    data () {
      return {
        loading: false,
        page: 1,
      }
    },
    methods: {
      async loadMore () {
        if (this.loading) {
          return;
        }
    
        this.page += 1;
        this.loading = true;
        const response = await this.somerequest();
    
        this.loading = false;
        // Oddly enough, we do nothing with the response
      }
    }
    

    现在,在模板中使用 v-ifv-else

    <button
      :disabled="loading"
      @click="loadMore"
    >
      <template v-if="loading">
        <icon name="loader" />
        Loading...
      </template>
      <template v-else>
        Load more
      </template>
    </button>
    

    如果您想将逻辑移动到不同的组件,您有两种选择:

    • loading 作为道具添加到该不同组件,并将模板代码移动到该组件
    • 使用插槽并将 html 直接传递到加载按钮。如果您有多种不同的配置,并且不想处理越来越复杂的配置选项以适应所有配置选项,这将特别有用。

    【讨论】:

    • 感谢您的帮助!
    猜你喜欢
    • 2014-02-05
    • 2013-02-23
    • 1970-01-01
    • 1970-01-01
    • 2018-07-03
    • 2021-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多