如何在Vue组件中定义变量?(Vue.JS 2)

10

我的 Vue 组件是这样的:

<template>
    <div>
        <div class="panel-group"v-for="item in list">
            <div class="col-md-8">
                <div class="alert">
                    {{ status = item.received_at ? item.received_at : item.rejected_at }}
                    <p v-if="status">
                        {{ status }} - {{ item.received_at ? 'Done' : 'Cancel' }}
                    </p>
                    <p v-else>
                        Proses
                    </p>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        ...
        computed: {
            list: function() {
                return this.$store.state.transaction.list
            },
            ...
        }
    }
</script>

我想定义status变量

所以,status变量可以用在条件语句中

我试过像这样:

{{ status = item.received_at ? item.received_at : item.rejected_at }}

但是,似乎它是错误的

我如何正确定义它?


为什么不使用 getter - Amresh Venugopal
2个回答

3
你需要使用数据
export default {
    ...
    data: function() {
        return {
            status: false
        }
    },
    computed: {
        list: function() {
            return this.$store.state.transaction.list
        },
        ...
    }
}

3

您可以使用一种方法,使得v-for作用域之外不存在item变量的功能得以实现。

 ...
 <div class="alert">
   <p v-if="status(item)">
      {{ status(item) }} - {{ item.received_at ? 'Done' : 'Cancel' }}
   </p>
   <p v-else>
      Proses
   </p>
 </div> 
 ...

在组件中:
methods: {
  ...
  status (item) {
    return (item) 
             ? (item.received_at) ? item.received_at : item.rejected_at
             : false
  }
  ...
}

item.received_at taken from the loop <div class="panel-group"v-for="item in list">. It is not readable in the computed - samuel toh
“item”必须是数据属性吗? - Amresh Venugopal
是的,我看到了。但似乎仍需要在 data() 中定义它。 - samuel toh
@samueltoh 加入计算的 status() 有帮助吗? - Amresh Venugopal
如果我添加:console.log(this.$store.state.transaction.list),结果为:https://postimg.org/image/4ff5ka345/ - samuel toh
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接