In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article introduces the relevant knowledge of "using Vue3.0 case analysis". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Initialize the environment
In the previous article, we built a development environment through vite, but in fact, vite is not perfect enough to support a complete project, so we still choose to use vue-cli scaffolding to build the environment.
The vue-cli version used by the editor is 4.5.4. If your version is older, you can use npm update @ vue/cli to upgrade the scaffolding version, and if it is not installed, you can install it through npm install @ vue/cli-g.
Create a new project using scaffolding
Open the terminal (cmd) in the workspace and initialize the project with the vue create my-vue3-test command
Select Manually select features in the first step to select the function manually
Then select by Space and arrow keys in turn.
Choose Vue version Babel TypeScript Router Vuex CSS Pre-processors Linter/Formatter
4. Then return to the car.
Then prompt to select the Vue version and select 3.x (Preview)
Use class-style component syntax? Select n, that is, enter n and enter
Then prompt Use Babel alongside TypeScript and enter y`
Use history mode for router input n
Then the css preprocessor selects Less
Eslint Select ESLint + Prettier
And then Lint on save and In dedicater config files.
Finally, enter all the way to complete the construction of the project.
Start the project
After creating a new project, enter cd my-vue3-test in the project, and then execute yarn serve to start the project.
After startup, you can access the project by visiting http://localhost:8080/
Configure ant design vue
At a time when the official version of Vue3.0 has not yet been released, the well-known front-end UI libraries in China are the first to inherit Vue3.0 to their own UI libraries, the PC side is mainly ant-design-vue, and the mobile end is mainly vant. All the sample code in this article will be based on ant-design-vue. First, let's install ant-design-vue.
Installation dependency
Yarn add ant-design-vue@2.0.0-beta.6 yarn add babel-plugin-import-D
Configure ant-design-vue to load on demand
Go to the root directory of the project, then open the babel.config.js file and change the contents to
Module.exports = {presets: ["@ vue/cli-plugin-babel/preset"], plugins: [/ / demand load ["import", / / style loads less files for true {libraryName: "ant-design-vue", libraryDirectory: "es", style: "css"}]]}
Try to use vue3 + antdv to add a small page, we will directly replace the code in the views/Home.vue file with
Log in to 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};}}
Then restart the project and you will find that you can use ant-design-vue normally.
Setup of Vue3.0 New experience
For the advent of Vue3.0, the most attractive is Vue3.0 's Composition API, for Componsition API, it can be said that polarization is particularly serious, some people particularly like this new design and development method, while others feel that it is easy to write spaghetti-style code using Composition API (maybe this part of people don't know Lanzhou ramen). In the end, the editor doesn't comment on whether Composition API is good or bad. Anyway, I'm just a brick lifter. The setup introduced in this section is the entrance to Composition API.
Setup introduction
Setup is a new property provided by Vue3.0, and you can use Composition API in setup. In the above sample code, we have used setup. In the above code, we initialized a responsive data in setup through reactive, and then returned an object through return. The object contains declared responsive data and a method, and this data can be used directly in template, as in the code above. About reactive, I will explain it to you in the next section.
Parameter description of setup
The setup function takes two parameters, props and context.
Props
Props, the first parameter of the setup function, is a property passed in from outside the component, which is basically consistent with the props of vue2.0, 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 setup, props cannot be deconstructed, that is, the above code cannot be rewritten to
Setup ({value}) {console.log (value)}
Although the object returned by setup is used in template, for props, we do not need to return it in setup, but we can use it directly in template. For example, the value above can be written directly in template.
Context
Context is the second argument to the setup function, and context is an object that contains three properties, namely
Attrs
Attrs is the same as Vue2.0 's this.$attrs, that is, externally incoming properties that are not defined in props. For attrs, like props, we cannot use the deconstruction of es6 for attrs. We must use the writing method of attrs.name.
Slots
Slots corresponds to the slot of the component, and corresponds to the this.$slots of Vue2.0. Like props and attrs, slots cannot be deconstructed.
Emit
Emit corresponds to the this.$emit of Vue2.0, that is, external exposure events.
Setup return value
The setup function generally returns an object, which contains data and some functions or events to be used in the component template, but setup can also return a function, which corresponds to the render function of Vue2.0. You can use JSX in this function. For the use of JSX in Vue3.0, Xiaobian will explain it to you in a later series of articles.
Finally, it is important to note that do not use this in setup, the this in setup is different from the this you really want to use, through props and context can basically meet our development needs.
To learn about Composition API, start with reactive and ref
When using Vue2.0, we usually declare the properties of a component like the following code
Export default {data () {return {name:', sex: 'male'}
Then you can use it where you need it, such as computed,watch,methods,template, but there is an obvious problem, that is, the place where I declare data and the place where data is used may be far away from each other in the code structure, there is a feeling that you live at the head of the Yangtze River, I live at the end of the Yangtze River, and you don't see it every day. One of the most important reasons for the birth of Composition API is to solve this problem. In Youda's motivation for Composition API, the problem to be solved is described as follows:
As the functionality grows, 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 by options, but sometimes it makes more sense to organize code by logical relationships.
Currently, 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 Compositon API.
Introduction to reactive
In Vue2.6, a new api,Vue.observer appears, through which you can create a responsive object, and reactive is basically the same as Vue.ovserver. First, let's look at an example.
{{state.name}} import {reactive} from "vue"; export default {setup () {/ / declare a responsive object const state = reactive ({name: ""}) via reactive; / / modify it to W3Cschool setTimeout (() = > {state.name = "W3Cschool";}, 1000 * 5) in 5 seconds / / add state to an object and return return {state};}}
The above example is a basic use of reactive. We can see from the above code that reactive and Vue.observer declare responsive objects in a similar 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 has obviously changed the value, but the interface is not refreshed, so we need to use Vue.set to solve this problem. This problem is because the Object.defineProperty used by Vue2.0 can not listen to some scenarios, such as new attributes, but the problem is solved through Proxy in Vue3.0. So we can add new properties directly to the object declared by reactive. Let's take a look at the following example
Name: {{state.name}} website: {{state.wz}} import {reactive} from "vue"; export default {setup () {const state = reactive ({name: ""}); / / add attribute wz W3Cschool.cn setTimeout (() = > {state.wz = "W3Cschool.cn";}, 1000 * 5) after 5 seconds; return {state};}}
Although the above example does not declare the gzh attribute in state, we can directly add the gzh attribute to state after 5s. At this time, we do not need to use Vue.set to solve the problem that the new attribute is unresponsive.
In the above code, reactive returns a state by passing in an object. It is important to note that state is not used with the incoming object. Reactive does not modify the original object, but returns a brand new object, which is an instance of Proxy. It is important to note that you should try to use the responsive objects returned by reactive instead of the original objects in your project.
Const obj = {} const state = reactive (obj) / / output falseconsole.log (obj = state) introduce ref
If we need to declare the user's information in a function now, we may have two different ways to write it.
/ / 1let name =''let wz =' W3Cschool.cn'// '2let userInfo = {name:', wz: 'W3Centr.cn'}
The above two different declaration methods are also different when we use them. For method 1, we can use variables directly, while for method 2, we need to write it as userInfo.name. We can find that the way userInfo is written is similar to that of reactive, and Vue3.0 also provides another way of writing, just like method 1, that is, ref. Let's take a look at an example.
Name: {{name}} import {ref} from "vue"; export default {setup () {const name = ref (""); console.log ('name', name.value) / / modify name to W3Cschool setTimeout (() = > {name.value = "W3Cschool";}, 1000 * 5); return {name};}}
Through the above code, you can compare the difference between reactive and ref
Reactive passes in an object and returns a responsive object, while ref passes in a basic data type (in fact, a reference type can also be used), and returns the responsive value of the incoming value
Reactive can obtain or modify attributes directly through state.prop, while the return value of ref needs to be modified or read by name.value. It is important to note, however, that it is not necessary to get a value through .value in template, because knowledge has been done in template.
Elegant use of v-model in Vue3.0
V-model is not a new feature of vue3.0, we have a lot of v-model in Vue2.0, but there is a big difference between V3 and V2. In this section, we will mainly show you how to use v-model in Vue3.0 to provide surprises and how to customize v-model in Vue3.0.
Using v-model in Vue2.0 and Vue3.0
How to implement bidirectional data binding in Vue2.0? There are two common ways, one is v-model, the other is .sync, why are there two? This is because a component can only be used for one v-model, but some components need to have multiple data that can respond in both directions, so .sync appears. In order to achieve unification in Vue3.0, it is implemented that a component can have multiple v-model, while .sync is deleted. As in the following code, it is the difference between Vue2.0 and Vue3.0 using v-model.
Using v-model in Vue2.0
Export default {data () {return {value:',};},}
Using v-model in Vue3.0
Export default {/ / you can also continue to use the word data () {return {value:',};},} in Vue3.0.
In vue3.0, v-model needs to be followed by a modelValue, that is, the name of the property to be bound in both directions. Vue3.0 implements multiple v-model by assigning different modelValue to different v-model. The principle of v-model is explained below through a custom v-model.
Customize v-model use Vue2.0 to customize a v-model example
Component code
Export default {props: {type: String, default:''}}, methods: {$_ handleChange (e) {this.$emit ('input', e.target.value)}
2. Using components in your code
Export default {data () {return {value:''}
In Vue2.0, we achieve v-model by setting a property named value for the component and triggering an event named input. Of course, you can also modify the property name and event name through model, as detailed in my previous article.
Customize a v-model example using Vue3.0
Component code
Export default {props: {value: {type: String, default: ""}}, name: "CustomInput", setup (props, {emit}) {function _ handleChangeValue (e) {/ / vue3.0 is the emit ("update:value", e.target.value) that updates v-model through the emit event named update:modelValue } return {_ handleChangeValue};}}
In Vue3.0, because a component supports multiple v-model, there is a new change in the way v-model is implemented. First of all, we do not need to use a fixed property name and event name, in the above example, because it is an input input box, we still use value for the property name, but it can also be anything else, such as name,data,val, etc., and the event name exposed after the value change becomes update:value, that is, update: property name. Where the component is called, the v-model: attribute name is used to distinguish between different v-model.
Using components in your code
Import {reactive} from "vue"; import CustomInput from ".. / components/custom-input"; export default {name: "Home", components: {CustomInput}, setup () {const state = reactive ({inputValue: ""}); return {state};}; "using Vue3.0 instance Analysis" ends here. Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.