The most recent event is the release of VUe3.0 by Yu Yuxi, which has not finished learning 3.0 yet. Really technology update speed is too fast, I feel that I can’t keep up, but then again, how can I not learn to reflect their own value, learn! , first share the basics of Vue2.5 +.

componentization

  1. Begin to use

    • The introduction of the component

      import Cart from './components/Cart'
      Copy the code
    • To register a component, use Components

      components:{
            Cart
          },
      Copy the code
    • use

      <Cart> </Cart> uses Cart to reference componentsCopy the code
  2. Component data transfer

    • The father passes on the son

      • Parent component: Passes data using the form :name

        <Cart :name="name" :cart="cart"></Cart> <! --> <script> import Cart from './components/Cart' export default {name:'app', Components :{Cart}, data(){return{name:' Cart ', Cart :[]}},} </script>Copy the code
      • Subcomponent: receives using props

        <script> export default {// You can use props to validate data :{name:{type:String, // The type is String required:true // The data must be passed}, Cart :{type: Array}}, </script>Copy the code
    • The son of a father passes on to the father

      • Child component: We can trigger an event to the parent component by calling the built-in $emit method and passing in the event name

        <button v-on:click="$emit('enlarge-text')"> Enlarge text </button> <! < grid V-on :click="$emit('enlarge-text', 0.1)"> enlarge text </ grid >Copy the code
      • Parent: When listening for this event, we can access the value thrown by $event

        <blog-post v-on:enlarge-text="postFontSize += $event" ></blog-post> <! Or if the event handler is a method, >< blog-post V-on :enlarge-text="onEnlargeText" ></blog-post> <script> methods: {onEnlargeText: function (enlargeAmount) { this.postFontSize += enlargeAmount } } </script>Copy the code
    • Data transfer between two unrelated components

      Each vUE instance has a subscription/publish implementation that uses $on and ¥emit to pass data

      • The parent component broadcasts data

        <template> <li class="cart-list" v-for="(item, Key ="item.text"> <span>{{item.text}}</span> <span>¥{{item.price}}</span> <span> button @click="addCart(index)" </button> </li> </template> <script> export default {// { addCart(i){ const good = this.goods[i]; / / triggers an event to send this $bus. $emit (' addCart 'good)},}}, < / script >Copy the code
      • The child component listens for time to receive

        Data (){return {cart:[]}}, created(){this.$bus.$on('addCart', Good =>{const ret = this.cart.find(v=>v.text=== =good.text); }) }, } </script>Copy the code

The style and class

  1. Style: Inline style V-bind :style, which can be shortened to :style

    <tr v-for="(c,i) in cart" :key="c.text" :style="{color:c.active? 'red':'black'}"> {{i}} </tr>Copy the code
  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>
    Copy the code

Calculate attribute

  1. With computed fields, you can compute abundance logic

    <td colspan="2">{{activeCount}}/{{count}}</td> <td colspan="2">{{total}}</td> <! Total () --> <script> export default {// Although methods can be used, computed has a value, And do not write parentheses after methods () 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. }, activeCount(){return this.cart.filter(v=>v.active).length; } }, </script>Copy the code

The mock data

Mock data, also known as mock data, is separated from the front and back ends

Create a new vue. Config. js extension to webpack Settings

module.exports ={
  configureWebpack: {
      devServer: {before(app) {
              app.get('/api/goods'.function (req,res) {
                  res.json({
                      list:[
                          {text:"Million dollar architect".price:100},
                          {text:"Web Full Stack Architect".price:80},
                          {text:"Python crawler".price:70},
                          {text:"Java Architect".price:90}]})})}}}};Copy the code

Use AXIos for the request

import axios from 'axios';  // Need to download the AXIos module
created() {
    axios.get('/api/goods').then(res= >{
        this.goods = res.data.list; })},Copy the code

Data persistence

For us, shopping cart data cannot disappear every time we refresh, so we need to cache data, that is, persist data

// Define the method setLocal
methods: {setLocal(){
        window.localStorage.setItem('cart'.JSON.stringify(this.cart)); }}// Listen for data changes
watch: {cart:function () {
        this.setLocal()
    }
},
// Obtain the data stored locally
created(){
    this.cart = JSON.parse(window.localStorage.getItem('cart') | | []; },Copy the code

Cycle to monitor

watch:{
    cart: {handler() {
            this.setLocal();
        },
            deep:true.// Deep monitor
    }
Copy the code

支那