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

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.

主站蜘蛛池模板: 焦作市| 盐亭县| 杭锦后旗| 岚皋县| 兴国县| 方山县| 观塘区| 镇巴县| 论坛| 平凉市| 蒙自县| 榆树市| 汕头市| 隆子县| 交城县| 永春县| 福建省| 白山市| 久治县| 防城港市| 宾阳县| 夏津县| 明水县| 彭阳县| 南乐县| 洛宁县| 安塞县| 宜兴市| 黔江区| 大厂| 汉沽区| 弥渡县| 汉阴县| 岳池县| 新化县| 鄄城县| 阿合奇县| 大安市| 临邑县| 绿春县| 漠河县|