vue-watch和computed

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>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

奇葩也是花

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值