What knowledge points have I gained by using vue3.0 (1)

Time:2021-5-12

The front-end development is full of flowers, and one skill is not yet mature.
At a loss, I don’t know what to do. I pay close attention to the small editor’s success.

I feel very busy recently. I don’t have much time to write articles. Today’s article is mainly about my early studyVue3.0Some of the notes are summarized. You can finish them by yourself after reading this articleVue3.0Environment construction, but also toVue3.0Some of the new features to understand, to facilitate their ownVue3.0We need to learn more. This article starts with the official account [front end play].===Yes, there are more interview questions waiting for you to brush.

All examples in this article useant design vue2.0Implementation, aboutant design vue2.0Please refer tohttps://2x.antdv.com/docs/vue/introduce-cn/

Initialization environment

In the previous article, we usedviteBuilt a development environment, but actually nowviteIt is not perfect enough to support a complete project, so we still choose to use it in this articlevue-cliScaffold is used to build environment.

The use of Xiaobianvue-cliThe version is4.5.4, if your version is older, you cannpm update @vue/cliTo upgrade the scaffold version, if it is not installed, you cannpm install @vue/cli -gInstall

New project using scaffold

  1. Open the terminal in the workspace(cmd), and then throughvue create my-vue3-test Command initialization project
  2. Choose first in the first stepManually select featuresFor manual selection
  3. And then throughSpaceAnd the up and down keys in turn

    Choose Vue version
    Babel
    TypeScript
    Router
    Vuex
    CSS Pre-processors
    Linter/Formatter

    Then enter

    1. Then prompt for selectionVueVersion, select3.x(Preview)
    2. Use class-style component syntax?choicen, i.e. inputnThen enter
    3. Then promptUse Babel along side typescript, inputy`
    4. Use history mode for routerinputn
    5. thencssPreprocessor selectionLess
    6. eslintchoiceESLint + Prettier
    7. And then there’s theLint on saveandIn dedicater config files
    8. The project can be completed by the last return

Start project

After creating a new project, enter the projectcd my-vue3-test, and then executeyarn serveYou can start the project

After startup, you can access the http://localhost:8080/ Visit project

to configureant design vue

At presentVue3.0Before the official version was released, it was a well-known front-end in ChinaUITake the lead in the libraryVue3.0Integrated into your ownUIIn the library,PCThe end is mainlyant-design-vueMobile terminals are mainlyvantAll the sample code in this article will be based onant-design-vueFirst, let’s install itant-design-vue

  1. Installation dependency

    yarn add [email protected]
    yarn add babel-plugin-import -D
  2. to configureant-design-vueLoad on demand

    Go to the root of the project and open itbabel.config.jsFile, change the content to

    module.exports = {
      presets: ["@vue/cli-plugin-babel/preset"],
      plugins: [
        //Load on demand
        [
          "import",
          //Load less file if style is true
          { libraryName: "ant-design-vue", libraryDirectory: "es", style: "css" }
        ]
      ]
    };
  3. Try to usevue3 + antdvTo add a small page, we willviews/Home.vueReplace the code in the file with
<template>
  <a-form layout="inline" :model="state.form">
    <a-form-item>
      <a-input v-model:value="state.form.user" placeholder="Username">
        <template v-slot:prefix
          ><UserOutlined style="color:rgba(0,0,0,.25)"
        /></template>
      </a-input>
    </a-form-item>
    <a-form-item>
      <a-input
        v-model:value="state.form.password"
        type="password"
        placeholder="Password"
      >
        <template v-slot:prefix
          ><LockOutlined style="color:rgba(0,0,0,.25)"
        /></template>
      </a-input>
    </a-form-item>
    <a-form-item>
      <a-button
        type="primary"
        :disabled="state.form.user === '' || state.form.password === ''"
        @click="handleSubmit"
      >
        Sign in
      </a-button>
    </a-form-item>
  </a-form>
</template>
<script>
import { UserOutlined, LockOutlined } from "@ant-design/icons-vue";
import { Form, Input, Button } from "ant-design-vue";
import { reactive } from "vue";

export default {
  components: {
    UserOutlined,
    LockOutlined,
    [Form.name]: Form,
    [Form.Item.name]: Form.Item,
    [Input.name]: Input,
    [Button.name]: Button
  },
  setup() {
    const state = reactive({
      form: {
        user: "",
        password: ""
      }
    });

    function handleSubmit() {
      console.log(state.form);
    }

    return {
      state,
      handleSubmit
    };
  }
};
</script>

Then restart the project, you can find that it can be used normallyant-design-vueIt’s too late.

Setup for new experience of vue3.0

aboutVue3.0What attracts people’s attention most is the advent of the new eraVue3.0OfComposition API, forComponsition APIIt can be said that the polarization is particularly serious. Some people especially like this new design and development method, while others feel like using itComposition APIIt’s easy to write spaghetti style code (maybe these people don’t know Lanzhou Ramen). to the endComposition APIWhether it’s good or bad, Xiaobian doesn’t comment. Anyway, I’m just a bricklayer. This section introducessetupnamelyComposition APIThe entrance to the hotel.

Introduction to setup

setupyesVue3.0Provides a new property that can be used insetupUsed inComposition APIIn the example code above, we have used itsetupIn the code above, wesetupPassed inreactiveInitialize a responsive data, and then pass thereturnReturns an object that contains the declared responsive data and a method, and the data can be used directlytemplateYes, just like in the code above. aboutreactiveI’ll give you an explanation in the next section.

Parameter description of setup

setupThe function has two argumentspropsandcontext

  1. props

    propsyessetupThe first parameter of the function is the incoming attribute outside the component, andvue2.0OfpropsBasically consistent, such as the following code

    export default {
      props: {
        value: {
          type: String,
          default: ""
        }
      },
      setup(props) {
        console.log(props.value)
      }
    }

    But it should be noted that in thesetupIn the middle,propsYou can’t use deconstruction, that is, you can’t rewrite the above code to

    setup({value}) {
        console.log(value)
     }

    althoughtemplateIs used insetupObject returned, but forpropsWe don’t need to be heresetupCan be returned directly in thetemplateUse, like the one abovevalue, which can be directlytemplatefinish writing sth.

    <custom-component :value="value"></custom-component>
  2. context

    contextyessetupThe second argument to the function,contextIs an object, which contains three properties, namely

    • attrs

      attrsAndVue2.0Ofthis.$attrsIt is the same, that is, the external input is not inpropsProperties defined in. aboutattrsAndpropsAgain, we can’t be rightattrsusees6Must be usedattrs.nameHow to write

    • slots

      slotsCorresponding to the slot of the component, andVue2.0Ofthis.$slotsIt is corresponding topropsandattrsThe same,slotsIt can’t be deconstructed.

    • emit

      emitCorresponding toVue2.0Ofthis.$emitThat is, external exposure.

Setup return value

setupFunctions usually return an object that contains the information to be used in the component templatedataWith some functions or events, butsetupYou can also return a function that corresponds toVue2.0OfrenderFunction, which can be used in this functionJSX, forVue3.0Used inJSX, Xiaobian will bring you more explanation in the following series of articles.

Last but not least, don’tsetupUsed inthis, insetupInthisAnd what you really needthisIt’s different. It’s differentpropsandcontextBasically, it can meet our development needs.

understandComposition API, start withreactiveandrefstart

in useVue2.0In general, we declare the properties of the component just like the following code

export default {
  data() {
    return {
      Name: 'Zijun',
      Sex: 'male'
    }
  }
}

And then it can be used where it needs to be, for examplecomputed,watch,methods,templateBut there is an obvious problem that I declaredataThe place and use ofdataThe places in the code structure may be far apart, there is a kind ofYou live at the head of the Yangtze River, I live at the end of the Yangtze River. I miss you every day, but I don't see you. I drink a river togetherIt’s a very good feeling. andComposition APIOne of the most important reasons for the birth of the Internet is to solve this problem. It’s about you da daComposition APIThe motivation for solving the problem is described as follows:

  1. With the growth of functions, the code of complex components becomes more and more difficult to read and understand. This is especially common when developers read code written by others. The root cause is that Vue’s existing API forces us to organize code through options, but sometimes it makes more sense to organize code through logical relationships.
  2. At present, there is a lack of a simple and low-cost mechanism to extract and reuse the logic between multiple components.

Now let’s take a lookCompositon APIInreactiveandref

introducereactive

stayVue2.6There is a new oneapi,Vue.observerThrough thisapiYou can create a responsive object, andreactiveJust likeVue.ovserverThe functions of are basically the same. Let’s start with an example

<template>
  <!-- Use the data returned in setup through state. Name in the template -- >
  <div>{{ state.name }}</div>
</template>
<script>
import { reactive } from "vue";
export default {
  setup() {
    //Declare a responsive object through reactive
    const state = reactive({
      Name: "Zijun"
    });
    //After 5 seconds, change Zijun to play in the front
    setTimeout(() => {
      State. Name = front end play;
    }, 1000 * 5);
    //Add state to an object and return
    return {
      state
    };
  }
};
</script>

This is the example abovereactiveA basic usage of, we can see through the above codereactiveandVue.observerThe methods of declaring responsive objects are similar, but there are some differences between them. We’re using itvue2.0One of the most common problems is that you often encounter some data that has changed the value, but the interface has not been refreshedVue.setTo solve this problem is becauseVue2.0UsedObject.definePropertyWe can’t listen to some scenarios, such as new attributes, but it’s timeVue3.0Passed inProxyThis problem has been solved, so we can directlyreactiveAdd new properties to the declared object. Let’s take a look at the following example

<template>
  <div>
    < div > Name: {{state. Name}} < / div >
    <div> official account:}}</div> state.gzh
  </div>
</template>
<script>
import { reactive } from "vue";
export default {
  setup() {
    const state = reactive({
      Name: "Zijun"
    });
    //Add attribute GZH after 5 seconds
    setTimeout(() => {
      State.gzh = front end play;
    }, 1000 * 5);
    return {
      state
    };
  }
};
</script>

Although the above example is in thestateThere is no statement in the reportgzhProperty, but in5sAfter that, we can give it to you directlystateadd togzhProperty, which is not required at this timeVue.setTo solve the problem that the new attribute cannot respond.

In the code above,reactiveBy passing in an object and then returning anstateIt should be noted thatstateIt is not used with the incoming object,reactiveThe original object is not modified, but a new object is returned. The returned object isProxyExamples of. It should be noted that in the project as far as possible to usereactiveThe returned responsive object, not the original object.

const obj = {}
const state = reactive(obj)
//Output false
console.log(obj === state)

introduceref

If we need to declare user information in a function now, we may have two different ways to write it

//Writing method 1
Let name ='zijun '
Let GZH ='play on the front end '
//Writing method 2
let userInfo = {
  Name: 'Zijun',
  GZH: 'some play at the front end'
}

The above two different declaration methods are also different when we use them. For the writing method1We can use variables directly, but forWriting method 2We need to writeuserInfo.nameIt’s the same way. We can find outuserInfoHow to write and how to writereactiveIt’s quite similar, andVue3.0It also provides another way of writing, likeWriting method 1The same, that isref. Let’s start with an example.

<template>
  <div>
    < div > Name: {name}} < / div >
  </div>
</template>
<script>
import { ref } from "vue";
export default {
  setup() {
    Const name = ref ("Zijun");
    Console.log ('name ', name. Value)
    //After 5 seconds, change the name to the front end
    setTimeout(() => {
      Name. Value = front end play;
    }, 1000 * 5);
    return {
      name
    };
  }
};
</script>

Through the above code, can be comparedreactiveAndrefThe difference between

  1. reactiveAn object is passed in, a responsive object is returned, andrefWhat is passed in is a basic data type (in fact, the reference type can also be used), and what is returned is the responsive value of the passed in value
  2. reactiveYou can get or modify properties directly through thestate.propTo operate, andrefThe return value needs to be passed through thename.valueTo modify or read data in the same way. But it should be noted that in thetemplateThere is no need to pass the.valueTo get the value, becausetemplateWe’ve done a set of understanding.

stayVue3.0Elegant usev-model

v-modelNot at allvue3.0New features launched inVue2.0We’ve got a lot of themv-model, butV3andV2There is a big difference. In this section, we will mainly bring you how toVue3.0Used inv-model,Vue3.0Inv-modelWhat’s the surprise and how toVue3.0Custom inv-model

stayVue2.0andVue3.0Used inv-model

stayVue2.0How to achieve two-way data binding? There are two commonly used ways, one isv-modelThe other is.syncWhy are there two? This is because a component can only be used for onev-modelHowever, some components need to have multiple data that can respond in both directions, so it appears.sync. stayVue3.0In order to achieve unification, a component can have multiple componentsv-modelAt the same time, it was deleted.sync. For example, the following codes areVue2.0AndVue3.0usev-modelThe difference between them.

  1. stayVue2.0Used inv-model

    <template>
      <a-input v-model="value" placeholder="Basic usage" />
    </template>
    <script>
    export default {
      data() {
        return {
          value: '',
        };
      },
    };
    </script>
  2. stayVue3.0Used inv-model

    <template>
      <!-- In vue3.0, V-model needs to be followed by a modelvalue, that is, the attribute name to be bidirectionally bound -- >
      <a-input v-model:value="value" placeholder="Basic usage" />
    </template>
    <script>
    export default {
      //You can also continue to use the writing method of 'vue2.0' in vue3.0
      data() {
        return {
          value: '',
        };
      },
    };
    </script>

    stayvue3.0In the middle,v-modelIt needs to be followed by onemodelValue, that is, the name of the property to be bidirectionally bound,Vue3.0It’s by giving differentv-modelSpecify differentmodelValueTo achieve multiplev-model. aboutv-modelThe principle of the following will be through customv-modelTo illustrate.

customv-model

useVue2.0Customize onev-modelExamples
  1. Component code
<template>
  <div class="custom-input">
    <input :value="value" @input="$_handleChange" />
  </div>
</template>
<script>
export default {
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  methods: {
    $_handleChange(e) {
      this.$emit('input', e.target.value)
    }
  }
}
</script>
  1. Using components in code

    <template>
        <custom-input v-model="value"></custom-input>
    </template>
    <script>
        export default {
        data() {
          return {
            value: ''
          }
        }
      }
    </script>

    stayVue2.0By setting thevalueProperty to trigger theinputEventv-modelOf course, it can also be passedmodelTo modify the property name and event name, you can see the details in my previous articles.

useVue3.0Customize onev-modelExamples
  1. Component code

    <template>
      <div class="custom-input">
        <input :value="value" @input="_handleChangeValue" />
      </div>
    </template>
    <script>
    export default {
      props: {
        value: {
          type: String,
          default: ""
        }
      },
      name: "CustomInput",
      setup(props, { emit }) {
        function _handleChangeValue(e) {
          //Vue3.0 is generated through the emit event named update:modelValue To update the
          emit("update:value", e.target.value);
        }
        return {
          _handleChangeValue
        };
      }
    };
    </script>
    1. Using components in code

      <template>
        <!-- When using V-model, you need to specify modelvalue -- >
        <custom-input v-model:value="state.inputValue"></custom-input>
      </template>
      <script>
      import { reactive } from "vue";
      import CustomInput from "../components/custom-input";
      export default {
        name: "Home",
        components: {
          CustomInput
        },
        setup() {
          const state = reactive({
            inputValue: ""
          });
          return {
            state
          };
        }
      };
      </script>

here we areVue3.0Because a component supports multiplev-modelSov-modelThere are new changes in the way of implementation. First of all, we don’t need to use fixed property names and event names. In the above example, because it isinputInput box, property name we still use isvalueBut it can be anything else, likename,data,valAfter the value changes, the exposed event name becomesupdate:value, i.eUpdate: property name. It is also used where the component is calledV-model: property nameTo distinguish between differentv-model

summary

In this paper, we mainly explain the construction of the development environment,setup,reactive,ref,v-modelAt the same time, through comparisonVue3.0AndVue2.0Let’s have a better understanding of the difference between the twoVue3.0With a certain understanding, we will bring you more introduction in the following, such as technical attributes,watch, life cycle, etc. This article starts with the official account [front end play].VueThe interview brush questions, do in the front of some play, ` Chengxing naked speech heart is very happy, interview work repeatedly suffered.
Thanks for one question every day, don’t be lazy, Next Monday, we’ll see you again.

epilogue

Don’t blow out your inspiration and imagination; Don’t be a slave to your model—— Vincent Van Gogh