【问题标题】:How can I add condition in button tag ? (vue.js 2)如何在按钮标签中添加条件? (vue.js 2)
【发布时间】:2017-07-07 19:38:16
【问题描述】:

我的组件代码是这样的:

    ...
    <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>

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

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

当状态=失败时,按钮如下所示:

<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>

但是,它不起作用

我该怎么做?

【问题讨论】:

  • 您最好在点击处理函数中检查条件。继续或关闭模式。

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


【解决方案1】:

不能动态绑定事件监听器,

但您可以创建另一个函数并像这样检测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>

EDIT:好像你想关闭Bootstrap modal,那么你可以在doSomething()函数中取消注释$('#modal').modal('hide');

【讨论】:

  • 我在 doSomething 方法中做console.log(this.status),结果 = null。结果是成功还是失败
【解决方案2】:

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

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");

【讨论】:

  • 请注意,当您使用 Vue.js 时,不应该使用 jQuery 修改 DOM。修改 DOM 后,Vue.js 不会重新绑定事件监听器。
猜你喜欢
  • 2017-08-17
  • 2017-06-12
  • 2017-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多