classic 场景:我想显示一个列表,但当它为空时,我想显示"无数据".

做一些我认为简单的事情有点复杂,这让我觉得我可能做错了.

这是我目前的解决方案.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/vue/1.0.16/vue.js"></script>

<div id="element">
  <div v-if="empty">No item in inventory</div>
  <div v-for="(index, item) in inventory">
    {{item.key}}<button onclick="remove('{{index}}')">remove</button>
  </div>
</div>

<script type="text/javascript">
"use strict";
var vm;
$(function() {
    vm = new Vue({
        el: '#element',
        data: {
            inventory: {"id1" : {"key" : "val1"}, "id2" : {"key" : "val2"}},
            empty: false
        },
        watch: {
            inventory: function() {
                vm.empty = $.isEmptyObject(vm.inventory);
            }
        }
    });
});

function remove(key) {
  Vue.delete(vm.inventory, key);
}
</script>

还有比这更好的解决方案吗?

推荐答案

您可以在v-if中使用长度inventory,如下所示:

<div id="element">
  <div v-if="!inventory.length">No item in inventory</div>
  <div v-for="(index, item) in inventory">
      {{item.key}}
      <button v-on:click="remove(index)">remove</button>
  </div>
</div>

假设inventory变量是散列而不是数组,您可以使用以下任何一种方法来发现它是空的,并在v-if中使用它:

ECMA 5+:

Object.keys(inventory).length === 0

ECMA 5之前:

function isEmpty(obj) {
    for(var prop in obj) {
        if(obj.hasOwnProperty(prop))
            return false;
    }

    return JSON.stringify(obj) === JSON.stringify({});
}

由于您已经在使用jquery,您还可以执行以下操作:

jQuery.isEmptyObject({}); // true

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/vue/1.0.16/vue.js"></script>

<div id="element">

  <div v-if="isEmpty">No item in inventory</div>
  <div v-for="(index, item) in inventory">
      {{item.key}}<button @click="remove(index)">remove</button>
  </div>
</div>

<script type="text/javascript">
"use strict";
var vm;
$(function() {
    vm = new Vue({
        el: '#element',
        data: {
            inventory: {"id1" : {"key" : "val1"}, "id2" : {"key" : "val2"}},
            empty: false
        },
        methods: {
            remove: function(index) {
                Vue.delete(this.inventory, index);
                
            }
        },
        computed: {
           isEmpty: function () {
              return jQuery.isEmptyObject(this.inventory)
           }
       }
    });
});
</script>

Vue.js相关问答推荐

vuejs:在确认提示之前更改 HTML

我需要在 nuxt2 上使用 /index 作为 url 的一部分

如何在FormKit中验证文本输入框中不能输入数字

使用内部方法创建计算(computed)属性是否合法?

有没有办法将react 键作为值传递给由 v-for 创建的 v-model

在 v-for 中定义变量有什么问题吗?

仅在构建时为 Vue3 和 TailwindCSS 添加前缀

nuxt.js auth 始终重定向到登录,而不是允许转到带有 auth: false 的页面,

Vue,Composition API:如何从react 式转换中跳过深度嵌套的属性?

在 dom 内移动 Vue 组件?

如何从特定索引呈现 v-for

如何告诉 Vue 应用使用 Firebase 模拟器?

我可以修改 Vue.js VNodes 吗?

Vue 动态组件事件绑定

Vuex 存储数据总是驻留在内存中?

依赖关系甚至在 package.json 和 node_modules 中都没有定义

Vuejs获取事件正在调用的元素?

$emit 不会触发子事件

Axios 捕获错误请求失败,状态码 404

在Vue中调用方法时的括号