官术网_书友最值得收藏!

Binding attributes with v-bind

It would be helpful if a tooltip showed the number of notes we already had on the "Add note" button, wouldn't it? At least we can introduce another useful directive!

The tooltips are added with the title HTML attribute. Here is an example:

<button title="3 note(s) already">

Here, it is only a static text, though, and we would like to make it dynamic. Thankfully, there is a directive that allows us to bind a JavaScript expression to an attribute--v-bind. Like the v-on directive, it expects an argument, which is the name of the target attribute.

We can rewrite the preceding example with a JavaScript expression as follows:

<button v-bind:title="notes.length + ' note(s) already'">

Now, if you leave the mouse cursor over the button, you will get the number of notes:

Like the v-on directive, v-bind has a special shortcut syntax (both are the most used directives)--you can just skip the v-bind part and only put the : character with the attribute name. The example would look like this:

<button :title="notes.length + ' note(s) already'">

JavaScript expressions bound with v-bind will re-evaluate automatically when needed and update the value of the corresponding attribute.

We could also move the expression to a computed property and use it instead. The computed property could be as follows:

computed: {
  ...

  addButtonTitle () {
    return notes.length + ' note(s) already'
  },
},

Then, we would rewrite the bound attribute, as follows:

<button :title="addButtonTitle">
主站蜘蛛池模板: 夏津县| 特克斯县| 华池县| 蓝田县| 常宁市| 洪洞县| 吴堡县| 登封市| 宁河县| 西华县| 庆安县| 威信县| 普洱| 龙门县| 东阳市| 大厂| 乡城县| 沁水县| 长武县| 清水河县| 钟山县| 华蓥市| 安顺市| 张北县| 宜黄县| 昌吉市| 柏乡县| 静海县| 葫芦岛市| 绥棱县| 容城县| 永清县| 太白县| 凤山市| 伊宁市| 色达县| 永春县| 陈巴尔虎旗| 闽清县| 治多县| 梅河口市|