Vue从入门到实战:指令
来自CloudWiki
指令是带有v-前缀的特殊属性,其值限定为单个表达式。指令的作用是,当表达式的值发生改变时,将这个变化反映到DOM上。
例如,下面代码中v-if指令根据表达式show的值决定是否插入还是删除<p>元素。
<p v-if="show">你能看见我吗?</p>
此外,一些指令还可以带有参数,如v-bind,v-on指令
v-bind用于响应式的更新HTML属性,v-on指令用于监听DOM事件。
<a v-bind:href="url">中国水利水电出版社</a> <button v-on:click="sayGreet">Greet</button>
从Vue2.6开始,指令的参数可以是动态参数,示例如下:
<a v-bind:{{attribute}}="url">新浪网</a>
这里的attribute会被作为一个Javascript对象进行动态求值。
在DOM中使用模板时,还需要避免使用大写字符来命名动态参数。这是因为浏览器会把元素的属性名全部强制转换为小写字符。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Hello Vue.js</title> </head> <body> <!--View--> <div id="app"> <a v-bind:[attributeName] ="url">新浪网</a> <a v-bind:['hr' + param]="url">新浪网</a> </div> <script src="vue.js"></script> <script> var vm = new Vue({ el: '#app', data: { attributeName: "href", param: "ef", url: "http://www.sina.com.cn/" } }) </script> </body> </html>
会曝出错误:
[Vue warn]: Property or method "attributename" 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