Vue简单数据传递、模拟数据、数据持久化

最近的大事应该就是尤雨溪要推出vue3.0了,2.0还没学完3.0又出来了。真的技术更新速度太快了,感觉跟不上了,不过话又说回来了不学怎么能体现出自己的价值,学吧!,先分享一下vue2.5+的基础。

组件化

  1. 开始使用

    • 引入组件

      import Cart from './components/Cart'
      复制代码
    • 注册组件 ,使用components进行注册

      components:{
            Cart
          },
      复制代码
    • 使用

      <Cart> </Cart>  使用Cart来引用组件
      复制代码
  2. 组件数据传递

    • 父子关系之父传子

      • 父组件: 使用:name这种形式进行数据的传递

        <Cart :name="name" :cart="cart"></Cart> <!--使用:name这种形式进行数据的-->
        <script>
        import Cart from './components/Cart'
        export default {
            name:'app', //组件的名字
            components:{
              Cart
            },
            data(){
                return{
                    name:'开课吧',
                    cart:[]
                }
            },
        }
        </script>
        复制代码
      • 子组件:使用props进行接收

        <script>
            export default {  // 可以使用props进行数据验证
                props:{
                    name:{   
                        type:String,  //类型是string类型
                        required:true //数据必须传递
                    },
                    cart:{
                        type: Array  //数组类型
                    }
                },
        </script>
        复制代码
    • 父子关系之子传父

      • 子组件:我们可以调用内建的 $emit 方法并传入事件的名字,来向父级组件触发一个事件

        <button v-on:click="$emit('enlarge-text')">
          Enlarge text
        </button>
        <!--进行传出一个值-->
        <button v-on:click="$emit('enlarge-text', 0.1)"> 
          Enlarge text
        </button>
        复制代码
      • 父组件: 监听这个事件的时候,我们可以通过 $event 访问到被抛出的这个值

        <blog-post
          v-on:enlarge-text="postFontSize += $event"
        ></blog-post>
        <!--或者如果这个事件处理函数是一个方法,那么这个值将会作为第一个参数传入这个方法-->
        <blog-post
          v-on:enlarge-text="onEnlargeText"
        ></blog-post>
        <script>
            methods: {
                onEnlargeText: function (enlargeAmount) {
                    this.postFontSize += enlargeAmount
                }
            }
        </script>
        复制代码
    • 不相关的两个组件的数据传递

      vue每个实例都有订阅/发布模式的实现,使用$on和¥emit来传递数据

      • 父组件进行广播数据

        <template>
        	 <li class="cart-list" v-for="(item, index) in goods" :key="item.text">
                <span>{{item.text}}</span>
                <span>¥{{item.price}}</span>
                <button @click="addCart(index)" >添加购物车</button>
              </li>
        </template>
        <script>
            export default {  // 可以使用props进行数据验证
            	methods: {
                    addCart(i){
                        const good = this.goods[i];
                        // 触发一个事件  发送
                        this.$bus.$emit('addCart', good) 
                    },
                }
            },
        </script>
        复制代码
      • 子组件监听时间进行接收

        <script>
            export default {  // 可以使用props进行数据验证
            	 data() {
                    return {
                        cart:[]
                    }
                },
                created(){
                    this.$bus.$on('addCart', good=>{ //接收到数据
                        const ret = this.cart.find(v=>v.text===good.text);
                    })
                },
            }
        </script>
        复制代码

样式和class

  1. 样式 :内联样式 v-bind:style ,可以简写为:style

    <tr v-for="(c,i) in cart" :key="c.text" :style="{color:c.active?'red':'black'}">
    	{{i}}
    </tr>
    复制代码
  2. class

    <tr v-for="(c,i) in cart" :key="c.text" :class="{yellow_active:c.active}"></tr>
    <style scoped>
        tr.yellow_active{
            font-weight: bold;
            color: orange;
        }
    </style>
    复制代码

计算属性

  1. 使用computed字段,可以进行富足逻辑的计算

    <td colspan="2">{{activeCount}}/{{count}}</td>
        <td colspan="2">{{total}}</td>  <!-- 直接用 不用写total()-->
    <script>
        export default {    //虽然 也可以使用methods的方法实现 ,但是毕竟computed有它的价值,且再使用时不用写方法之后的括号()
        	data() {
                return {
                    cart:[]
                }
            },
           computed: {
                total() {
                    return this.cart.reduce((sum,v)=>{
                        if (v.active){
                            return sum+v.price*v.count;
                        }
                        return sum
                    },0)
                    // let num= 0;
                    // this.cart.forEach(v=>{
                    //     if (v.active){
                    //         num += v.price * v.count
                    //     }
                    // });
                    // return num
                },
                count() {  //购物车的所有商品条数
                    return this.cart.length;
                },
                activeCount(){  //选中的商品条数
                    return this.cart.filter(v=>v.active).length;
                }
            },
    </script>
    复制代码

mock数据

mock数据也就是模拟数据,进行前后端分离

简单的mock,使用自带的webpack-dev-serve即可实现,新建vue.config.js扩展webpack设置

module.exports ={
  configureWebpack: {
      devServer:{
          before(app) {
              app.get('/api/goods',function (req,res) {
                  res.json({
                      list:[
                          {text:"百万年薪架构师",price:100},
                          {text:"web全栈架构师",price:80},
                          {text:"Python爬虫",price:70},
                          {text:"Java架构师",price:90}
                      ]
                  })
              })
          }
      }
  }
};
复制代码

使用axios进行请求

import axios from 'axios';  //需要下载axios模块
created() {
    axios.get('/api/goods').then(res=>{
        this.goods = res.data.list;
    })
},
复制代码

数据持久化

对于我们来说购物车的数据不能每次刷新都消失,所以我们需要对数据进行数据的缓存,也就是数据的持久化

//定义方法 setLocal方法
methods:{
    setLocal(){
        window.localStorage.setItem('cart',JSON.stringify(this.cart));
    }
}
//监听数据变化
watch:{
    cart:function () {
        this.setLocal()
    }
},
//创建完成后获取本地存储的数据
created(){
    this.cart = JSON.parse(window.localStorage.getItem('cart'))||[];
},
复制代码

循环监听

watch:{
    cart:{
        handler() {
            this.setLocal();
        },
            deep:true, //深度监听
    }
复制代码

**

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享