computed:计算属性,它会根据数据动态显示新的计算结果。
watch: 监听数据的改变。一个数据需要被监听并且对数据做一些操作就用 watch
计算属性DEMO:
new Vue({
el: '#id',
template: `<div>
<span>Name: {{name}}<span>
</div>`,
data: {
firstName: 'Leo',
lastName: 'Alan'
},
computed: {
name () {
return `${this.firstName} + ${this.lastName}`
}
}
})
使用:
直接 {{name}} 即可
在list表监控数据改变展示出具体的结果。
<template>
<div class="hello">
<h1>{{title}}</h1>
<ul>
<li v-for="(v,k) in goodsList" :key="k">
<div style="border:1px solid red;margin-top:2px">
<span>商品ID:{{v.goods_id}}</span><br/>
<span>商品名字:{{v.goods_name}}</span><br/>
<span>商品价格Watch:{{v.goods_selfprice}}</span><br/>
<span>商品价格Computed:{{showPrice(v.goods_selfprice)}}</span>
</div>
</li>
</ul>
<template>
<button v-if="has_more" @click="loadMore()">点击加载更多</button>
<button v-else>我也是有底线的。。。</button>
</template>
</div>
</template>
<script>
import Common from "../mixin/Common";
export default {
name: 'demo',
mixins: [ Common ],
data () {
return {
title: 'GoodsList',
goodsList: [],
page: 1,
has_more: true
}
},
methods: {
loadMore: function () {
this.getGoodsList( this.page)
},
getGoodsList: function ( page ) {
this.$http.post('/api/getProductList', {page: this.page }).then((response) => {
this.goodsList = this.goodsList.concat(response.body.data.data)
this.page ++
if(response.body.data.data.length < 10 ){
this.has_more = false
}
}, (error) => {
console.log(error)
})
}
},
computed:{
showPrice:function ( ) {
return function ( price ){
console.log( price );
return '¥' + price;
}
}
},
watch:{
goodsList:function ( val ) {
// console.log( val );
for ( let i in val ){
this.goodsList[i].goods_selfprice = '¥' + val[i].goods_selfprice;
}
}
},
mounted() {
console.log( this.getUserToken() )
this.getGoodsList(1);
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
font-weight: normal;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display:block;
margin: 10px;
}
a {
color: #42b983;
}
.main{
color: red;
}
</style>