無效代碼:
<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之模板語法