如何在按钮标签中添加条件? (vue.js 2)

How can I add condition in button tag ? (vue.js 2)

我的组件代码是这样的:

    ...
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    ...
    <script>
        import { mapGetters } from 'vuex'
        export default{
            props:['idProduct'],
            computed: {
                ...mapGetters([
                    'status'
                ])
            },
            ...
    </script>

我想在按钮标签中添加条件。所以当 status = success 时,按钮看起来像这样:

<button type="button" class="btn btn-default" @click="reloadProduct">Close</button>

当 status = failure 时,按钮如下所示:

<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

从脚本标签组件中获取的状态值(参见计算)

我这样试:

<button type="button" class="btn btn-default" {{ status == 'success' ? @click="reloadProduct" : data-dismiss="modal"}}>
    Close 
</button>

但是,它不起作用

我该怎么做?

您不能动态绑定事件侦听器,

但您可以创建另一个函数并像这样检测 success 状态:

<button type="button" class="btn btn-default" @click="doSomething">Close</button>

<script>
    import { mapGetters } from 'vuex'
    export default {
        props:['idProduct'],
        computed: {
            ...mapGetters([
                'status'
            ])
        },
        methods: {
            doSomething(evt) {
                if (this.status === "success") {
                    // Call the reloadProduct() when the status is `success`.
                    reloadProduct()
                    // Remove the `data-dismiss` attribute of the button.
                    evt.target.removeAttribute("data-dismiss")
                } else {
                    // Add the `data-dismiss` attribute for the button.
                    evt.target.setAttribute("data-dismiss", "modal")
                    // Uncomment this if you're trying to close the modal.
                    // $('#modal').modal('hide');
                }
            }
        }
        ...
</script>

编辑:好像你想关闭Bootstrap模式,然后你可以在doSomething()函数中取消注释$('#modal').modal('hide');

这可能不是最佳答案,但它是一种解决方法。

if (status === success) {
  document.getElementById("yourDivHere").innerHTML = 
    '<button type="button" class="btn btn-default" @click="reloadProduct">
      Close
    </button>'
};

if (status === success) {
  document.getElementById("yourDivHere").innerHTML = 
    '<button type="button" class="btn btn-default" data-dismiss="modal">
      Close
    </button>'

更具体地说,您可以这样使用 jQuery:

$(this).attr("your attribute", "your value");