Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

What I gained with Vue 3.0 (i)


May 31, 2021 Article blog


Table of contents


This article is a summary of some of the notes you put together during your early study of Vue3.0 and by reading this article, you will be able to build your Vue3.0 environment, as well as learn about some of the new features of Vue3.0 so that you can learn Vue3.0 yourself.

All examples in this article are implemented using ant design vue2.0 and for ant design vue2.0 refer to 2x.antdv.com/docs/vue/introduce-cn/

Initialize the environment

In the previous article, we built a development environment with vite but now vite is not perfect enough to support a complete project, so in this article we still chose to use vue-cli scaffolding for environmental construction.

The vue-cli version used by the small editor is 4.5.4 and if your version is older you can upgrade the scaffolding version npm update @vue/cli and if you do not have an installation you can install it through npm install @vue/cli -g

Create a new project with scaffolding

  1. Open the terminal cmd in the workspace and initialize the project with vue create my-vue3-test command

  1. Select Manually select features first in the first step for manual selection

  1. Then select in turn via Space and the up and down keys

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

4. Then return

  1. Then prompt for Vue version and 3.x(Preview)
  2. Use class-style component syntax? Select n i.e. enter n and return
  3. Then prompt Use Babel alongside TypeScript,输入 y'
  4. Use history mode for router input n
  5. The css preprocessor then Less
  6. eslint ESLint + Prettier
  7. Then there's Lint on save and In dedicater config files
  8. The project can be completed with the last return train

Start the project

Once the project is complete, go to cd my-vue3-test in the project, and then execute yarn serve to start the project

Once started, you can access the project by accessing http://localhost:8080/

Configure ant design vue

At a time when the official Vue3.0 release is not yet available, the more UI front-end UI library in China is the first to inherit Vue3.0 into its own UI library, the PC side is mainly ant-design-vue the mobile side is mainly vant all the sample code in this article will be based on ant-design-vue first we install ant-design-vue

  1. Installation dependency

   yarn add ant-design-vue@2.0.0-beta.6
   yarn add babel-plugin-import -D

  1. Configure ant-design-vue to load on demand

Go to the root of the project, and then open babel.config.js file and modify the contents to

   module.exports = {
     presets: ["@vue/cli-plugin-babel/preset"],
     plugins: [
       // 按需加载
       [
         "import",
         // style 为 true 加载 less文件
         { libraryName: "ant-design-vue", libraryDirectory: "es", style: "css" }
       ]
     ]
   };

  1. Try adding a small page using vue3 + antdv and we'll replace the code in the views/Home.vue file directly 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"
      >
        登录
      </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 and you'll find that you're ready to use ant-design-vue

Setup for Vue 3.0's new experience

For the advent of Vue3.0 the most attention-grabbing is Vue3.0 Composition API for Componsition API can be said to be particularly polarized, some people particularly like this new design and development approach, while others feel that using Composition API is easy to write spaghetti code (perhaps this part of the people do not know Lanzhou ramen bar). I n the end Composition API is good or bad, small editor do not comment, anyway, I am just a brick move. The setup described in this section is the entry point to the Composition API

Introduction to setup

setup is a new property provided by Vue3.0 that allows you to use Composition API in setup we've used setup in the sample code above, we reactive a responsive data in setup above, and then return an object with declared responsive data and a method, and the data can be used directly in template as in the code above. With regard to reactive I'll give you instructions in the next section.

The parameter description of setup

setup function has two props and context

  1. props

props is the first argument to the setup function, a property that comes in from outside the component and is basically the same as the props of vue2.0 such as the following code

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

Note, however, that in setup props cannot be deconstructed, i.e. the above code cannot be rewritten

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

Although the object returned by setup is used in template for props we don't need to return in setup but can be used directly in template such as value above, and can be written directly in template

   <custom-component :value="value"></custom-component>

  1. context

context is the second argument of the setup function, context is an object that contains three properties, namely

  • attrs

attrs are the same as Vue2.0 this.$attrs which is an externally incoming property that is not defined in props For attrs as with props we cannot deconstruct attrs using es6 and we must use the writing of attrs.name

  • slots

slots correspond to the slots of the component, which correspond this.$slots of Vue2.0 and, like props and attrs slots cannot be deconstructed.

  • emit

emit corresponds to Vue2.0 i.e. exposure events. this.$emit

Setup returns a value

The setup function typically returns an object that contains data and some functions or events to be used in the component template, but setup can also return a function that corresponds to Vue2.0 render function, where you can use JSX and JSX for Vue3.0 which will be explained in a later series.

Finally, it's important to note that don't setup this in setup this in setup is different from this you really want to use, and that props and context basically meet our development needs.

Learn about Composition API starting with reactive and ref

When using Vue2.0 we generally declare the properties of the component like the following code

export  default {
  data() {
    return {
      name: '编程狮',
      sex: '男'
    }
  }
}

Then you can use in the need to use places such as computed watch methods template and so on, but there is a more obvious problem, that is, I declare data place of data and the use of data in the code structure may be far apart, there is a kind of King live in 君住长江头,我住长江尾,日日思君不见君,共饮一江水 feeling. O ne of the most important reasons for the birth of the Composition API is to solve this problem. In particular, the problem described in the motivations for the Composition API is as follows:

  1. As functionality grows, the code of complex components becomes more difficult to read and understand. T his is especially common when developers read code written by others. The root cause is that Vue's existing APIs force us to organize code through options, but sometimes it makes more sense to organize code through logical relationships.
  2. There is a lack of a concise and low-cost mechanism to extract and reuse logic between multiple components.

Now let's take a look at reactive and ref in the Compositon API

Introduce reactive

In Vue2.6 a new api Vue.observer api that creates a responsive object, and reactive is basically the same as Vue.ovserver functionality. Let's start with an example

<template>
  <!--在模板中通过state.name使用setup中返回的数据-->
  <div>{{ state.name }}</div>
</template>
<script>
import { reactive } from "vue";
export default {
  setup() {
    // 通过reactive声明一个可响应式的对象
    const state = reactive({
      name: "编程狮"
    });
    // 5秒后将编程狮修改为 W3Cschool
    setTimeout(() => {
      state.name = "W3Cschool";
    }, 1000 * 5);
    // 将state添加到一个对象中然后返回
    return {
      state
    };
  }
};
</script>

The above example is a basic usage of reactive and we can see from the code above that reactive and Vue.observer declare responsive objects in much the same way, but there are some differences between them. When we use vue2.0 one of the most common problems is that we often encounter some data that explicitly modifies the value, but the interface is not refreshed, this time we need to use Vue.set to solve this problem because Vue2.0 uses Object.defineProperty can not listen to certain scenarios such as new properties, but in Vue3.0 through Proxy to solve this problem, so we can directly on the object declared by reactive to add a new property, let's look at the following example

<template>
  <div>
    <div>姓名:{{ state.name }}</div>
    <div>网站:{{ state.wz }}</div>
  </div>
</template>
<script>
import { reactive } from "vue";
export default {
  setup() {
    const state = reactive({
      name: "编程狮"
    });
    // 5秒后新增属性wz W3Cschool.cn
    setTimeout(() => {
      state.wz = "W3Cschool.cn";
    }, 1000 * 5);
    return {
      state
    };
  }
};
</script>

Although the gzh property is not declared in state the above example does not declare the gzh property, but after 5s we can add gzh property directly to state and we do not need to use Vue.set to solve the problem where the new property does not respond.

In the code above, reactive passes in an object and then returns a state noting that state is not used with the incoming object, reactive does not modify the original object, but returns a brand new object that returns an instance of Proxy It is important to note that you try to use the responsive object returned by reactive in your project, not the original object.

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

Introduces ref

If now we need to declare the user's information in a function, we might have two different ways of writing

// 写法1
let name = '编程狮'
let wz = 'W3Cschool.cn'
// 写法2
let userInfo = {
  name: '编程狮',
  wz: 'W3Cschool.cn'
}

The above two different declarations, we use different, for writing 1 we can use variables directly, and for 写法2 we need to write as userInfo.name way. W e can see that userInfo is written in a similar way to reactive and Vue3.0 provides another way of writing, just like 写法1 which is ref Let's start with an example.

<template>
  <div>
    <div>姓名:{{ name }}</div>
  </div>
</template>
<script>
import { ref } from "vue";
export default {
  setup() {
    const name = ref("编程狮");
    console.log('姓名',name.value)
    // 5秒后修改name为 W3Cschool
    setTimeout(() => {
      name.value = "W3Cschool";
    }, 1000 * 5);
    return {
      name
    };
  }
};
</script>

With the code above, you can compare the difference between reactive and ref

  1. reactive passes in an object that returns a responsive object, while ref passes in a basic data type (in fact, reference types can also) and returns a responsive value of the incoming value
  2. reactive gets or modifies properties directly through state.prop and ref return value needs to modify or read the data through name.value Note, however, template that you don't need to get values through .value in template because you already have an understanding set in template

Use v-model gracefully in Vue3.0

v-model is not a new feature of vue3.0 we've got a lot of v-model in Vue2.0 but V3 and V2 are still very different. In this section we'll focus on how to use v-model in Vue3.0 and what surprises v-model in Vue3.0 provides and how to customize v-model in Vue3.0

Use v-model in Vue2.0 and Vue3.0

How do I achieve two-way data binding in Vue2.0 T here are two common ways, one is v-model and the other is .sync T his is because a component can only be used for one v-model but some components require more than one data that can respond in both .sync I n Vue3.0 in order to achieve unification, a single component can have multiple v-model while removing .sync As the code below, the difference Vue2.0 and Vue3.0 using v-model

  1. Use v-model in Vue2.0

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

  1. exist Vue3.0 In use v-model

   <template>
     <!--在vue3.0中,v-model后面需要跟一个modelValue,即要双向绑定的属性名-->
     <a-input v-model:value="value" placeholder="Basic usage" />
   </template>
   <script>
   export default {
     // 在Vue3.0中也可以继续使用`Vue2.0`的写法
     data() {
       return {
         value: '',
       };
     },
   };
   </script>

In vue3.0 v-model is followed by a modelValue the property name to bind in both directions, and Vue3.0 implements multiple v-models by assigning different modelValue to different v-model v-model For the principle of v-model the following will be explained by customizing v-model

Custom v-model

Use Vue2.0 to customize a v-model example

  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>

2 . Use components in your code

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

In Vue2.0 we implemented v-model by setting an event called value property for the component to trigger an event called input at the same time, and of course we can modify the property name and event name by model as detailed in my previous article.

Use Vue3.0 to customize a v-model sample

  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 是通过emit事件名为 update:modelValue来更新v-model的
         emit("update:value", e.target.value);
       }
       return {
         _handleChangeValue
       };
     }
   };
   </script>

In Vue3.0 the way v-model implemented has changed because one component supports multiple v-model F irst of all, we don't need to use a fixed property name and event name, in the example above, because it's input input box, the property name we're still using value but it can also be anything else like name data val and so on, and the event name that is exposed to the public after a change in value update:value that update:属性名 Where the component is called, v-model:属性名 used to distinguish between different v-model

  1. Use components in your code

<template>
  <!--在使用v-model需要指定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>

summary

In this article, we mainly explained the development environment, setup reactive ref v-model etc. , and by comparing the difference Vue3.0 and Vue2.0 let everyone have a certain understanding of Vue3.0

Above is W3Cschool编程狮 about the use of Vue3.0, I gained some knowledge points (i) related to the introduction, I hope to help you.