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

  • Vue.js 2.x by Example
  • Mike Street
  • 325字
  • 2021-07-02 20:00:30

Using component data and methods

As Vue components are self-contained elements of your Vue app, they each have their own data and functions. This helps when re-using components on the same page, as the information is self-contained per instance of a component. methods and computed functions are declared the same as you would on the Vue app, however, the data key should be a function that returns an object.

The data object of a component must be a function. This is so that each component has its own self-contained data, rather than getting confused and sharing data between different instances of the same component. The function must still return an object as you would in your Vue app.

Create a new component called balance, add a data function and computed object to your component and an empty <p> to the template property for now:

      Vue.component('balance', {
template: '<p></p>',
data() {
return {

}
},
computed: {

}
});

Next, add a key/value pair to your cost data object with an integer and add the variable to your template. Add the <balance></balance> custom HTML element to your view and you should be presented with your integer:

      Vue.component('balance', {
template: '<p>{{ cost }}</p>',
data() {
return {
cost: 1234
}
},
computed: {

}
});

As with our Vue instance in Chapter 1Getting Started with Vue.js, add a function to the computed object that appends a currency symbol to the integer and ensures there are two decimal places. Don't forget to add the currency symbol to your data function. 

Update the template to output the computed value instead of the raw cost:

      Vue.component('balance', {
template: '<p>{{ formattedCost }}</p>',
data() {
return {
cost: 1234,
currency: '$'
}
},
computed: {
formattedCost() {
return this.currency + this.cost.toFixed(2);
}
}
});

This is a basic example of a component, however, it is quite restricted with the fixed cost on the component itself.

主站蜘蛛池模板: 镇远县| 绍兴市| 楚雄市| 肥西县| 民县| 伊吾县| 调兵山市| 锡林浩特市| 长泰县| 静宁县| 连州市| 衡阳市| 上思县| 墨玉县| 湟源县| 酒泉市| 漳浦县| 青河县| 吴堡县| 平邑县| 资源县| 大邑县| 佛学| 玉山县| 刚察县| 金乡县| 黑河市| 辽中县| 迁安市| 福鼎市| 阿拉善右旗| 朝阳县| 茂名市| 板桥市| 白玉县| 台湾省| 余姚市| 乌拉特后旗| 上杭县| 开封市| 台前县|