v-on:[eventName] 設置click後,點擊無效 - Vue

無效代碼:

<body>

    <div id="app">
        <a v-on:[eventName]="showAlert">顯示窗口</a>
    </div>

    <script>
        var vm = new Vue({
            el: "#app",
            data: {
                eventName: "click"
            },
            methods: {
                showAlert: function() {
                   alert("hello,dynamic")
                }
            }
        })
    </script>

點擊顯示窗口 沒有任何提示

並且控制檯報錯:
vue.js:634 [Vue warn]: Property or method "eventname" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.
vue.js:634 [Vue warn]: Invalid value for dynamic directive argument (expected string or null): undefined

解決方法

將Vue實例中的eventName修改爲eventname即可

原因:
參數表達式的寫法存在一些約束:

在 DOM 中使用模板時 (直接在一個 HTML 文件裏撰寫模板),還需要避免使用大寫字符來命名鍵名,因爲瀏覽器會把 attribute 名全部強制轉爲小寫:在 DOM 中使用模板時這段代碼會被轉換爲 v-bind:[someattr]。 除非在實例中有一個名爲“someattr”的 property,否則代碼不會工作。


參考鏈接:
一起學Vue之模板語法

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章