First understanding of vue3.0

Vue 3We have not yet officially released, but the Alphaversion has been released.

Although it is officially not recommended to use Vue 3it directly in a production environment , it is always good to learn in advance.

I learned shouting his mouth did not move, his hands still very honest open Vue 3document

Create project

VueThe official provides a github repository very intimately, so that we can quickly experience Vue 3the new features:

git clone https://github.com/vuejs/vue-next-webpack-preview.git vue3-start
cd vue3-start
复制代码
npm install or yarn intall
复制代码

After the development environment is ready, start the command:

npm run dev
复制代码

Open in the browser http://127.0.0.1:8080, you can see a simple counter page:

 

langch

 

 

Open package.json, the currently used vue version is:3.0.0-beta.2

Vue 3 new features

Vue 3The design goal is to be faster, smaller, and better supported TypeScript.

Some new features include:

1、Composition API 2、Multiple root elements 3、Suspense 4、Multiple V-models 5、Reactivity 6、Teleport 7、Transition 8、Remove Filter 9、App configuration

1、Composition API

Vue official release of the Composition APIofficial plugin, so that users can Vue2.xenjoy in Function Basebringing new experience.

In vue 3no need to install a separate plug, out of the box.

Open App.vue, you will see the setup()method:

<template>
  <img src="./logo.png">
  <h1>Hello Vue 3!</h1>
  <button @click="inc">Clicked {
   
   { count }} times.</button>
</template>

<script>
import { ref } from 'vue'

export default {
  setup() {
    const count = ref(0)
    const inc = () => {
      count.value++
    }

    return {
      count,
      inc
    }
  }
}
</script>

<style scoped>
img {
  width: 200px;
}
h1 {
  font-family: Arial, Helvetica, sans-serif;
}
</style>

复制代码

Composition API Mainly provide two major benefits:

1. Clear code structure 2. Eliminate duplication of logic

<template>
  <div class="counter">
    <p>count: {
   
   { count }}</p>
    <p>NewVal (count + 2): {
   
   { countDouble }}</p>
    <button @click="inc">Increment</button>
    <button @click="dec">Decrement</button>
    <p> Message: {
   
   { msg }} </p>
    <button @click="changeMessage()">Change Message</button>
  </div>
</template>
<script>
import { ref, computed, watch } from 'vue'
export default {
  setup() {
    /* ---------------------------------------------------- */
    let count = ref(0)
    const countDouble = computed(() => count.value * 2)
    watch(count, newVal => {
      console.log('count changed', newVal)
    })
    const inc = () => {
      count.value += 1
    }
    const dec = () => {
      if (count.value !== 0) {
        count.value -= 1
      }
    }
    /* ---------------------------------------------------- */
    let msg= ref('some text')
    watch(msg, newVal => {
      console.log('msg changed', newVal)
    })
    const changeMessage = () => {
      msg.value = "new Message"
    }
    /* ---------------------------------------------------- */
    return {
      count,
      inc,
      dec,
      countDouble,
      msg,
      changeMessage
    }
  }
}
</script>
复制代码

If you do not like Composition API, you can continue to use 2.xtraditional methods:

<template>
  <div class="counter">
    <p>count: {
   
   { count }}</p>
    <p>NewVal (count + 2): {
   
   { countDouble }}</p>
    <button @click="inc">Increment</button>
    <button @click="dec">Decrement</button>
    <p> Message: {
   
   { msg }} </p>
    <button @click="changeMessage()">Change Message</button>
  </div>
</template>
<script>
export default {
  data() {
    return {
      count: 0,
      msg: 'some message'
    }
  },
  computed: {
    countDouble() {
      return this.count*2
    }
  },
  watch: {
    count(newVal) {
      console.log('count changed', newVal)
    },
    msg(newVal) {
      console.log('msg changed', newVal)
    }
  },
  methods: {
     inc() {
      this.count += 1
    },
    dec() {
      if (this.count !== 0) {
        this.count -= 1
      }
    },
    changeMessage() {
      msg = "new Message"
    }
  }

}
</script>
复制代码

The above two pieces of code are completely equivalent in the effect listing

Use Composition APIbenefits: allows us to better organize the code ( state, methods, computed properties, watcheretc.).

As the scale of components grows, how to organize our business code has gradually become an important issue to ensure that new developers can easily understand the code without spending too much time.

Before we can use mixinto reuse code. However, the mixinbiggest pain point is that we need to track the states and methods in different components, which often brings a certain mental burden to the development. If we are not careful, mixinit may overwrite the existing states or methods in the components.

Use Composition APImake code reuse easier.

We can also extract the code of the repeated function:

// message.js
import { ref, watch } from "vue";
export function message() {
  let msg = ref(123);
  watch(msg, (newVal) => {
    console.log("msg changed", newVal);
  });
  const changeMessage = () => {
    msg.value = "new Message";
  };
  return { msg, changeMessage };
}
复制代码

Use the above components in other components:

<template>
  <div class="counter">
    <p>count: {
   
   { count }}</p>
    <p>NewVal (count + 2): {
   
   { countDouble }}</p>
    <button @click="inc">Increment</button>
    <button @click="dec">Decrement</button>
    <p>Message: {
   
   { msg }}</p>
    <button @click="changeMessage()">change message</button>
  </div>
</template>
<script>
import { ref, computed, watch } from 'vue'
import { message } from './common/message'
export default {
  setup() {
    let count = ref(0)
    const countDouble = computed(() => count.value * 2)
    watch(count, newVal => {
      console.log('count changed', newVal)
    })
    const inc = () => {
      count.value += 1
    }
    const dec = () => {
      if (count.value !== 0) {
        count.value -= 1
      }
    }
    let { msg, changeMessage } = message()
    return {
      count,
      msg,
      changeMessage,
      inc,
      dec,
      countDouble
    }
  }
}
</script>
复制代码

2、Multiple root elements

In Vue 2the, tempalte only take a root element. Even if we only have two <p> tags, we must include them in one <div> tag:

<template>
  <div class="counter">
    <p> Count: {
   
   { count }} </p>
    <button @click="increment"> Increment </button>
    <button @click="decrement"> Decrement</button>
  </div>
</template>
复制代码

In order to compile and pass, we usually add a root node.

This design is really bad, I have complained about this design countless times. Because it will bring unnecessary code nesting and indentation.

Fortunately Vue 3cancel this restriction:

You can use any number of tags directly in <template></template>:

<template>
  <p> Count: {
   
   { count }} </p>
  <button @click="increment"> Increment </button>
  <button @click="decrement"> Decrement </button>
</template>
复制代码

When you open a template with VScode, see some linterrors, because the official plug-in eslint-plugin-vuehas not yet support the new template syntax.

3、Suspense

SuspenseIt is a Vue 3new feature.

Usually around the end of the interaction is an asynchronous process: We provide a default Loading animation, when used in conjunction with data returned v-ifto the control data display.

SuspenseHas significantly simplifies this process: it provides defaultand fallbacktwo states:

<template>
  <Suspense>
    <template #default>
      <div v-for="item in articleList" :key="item.id">
        <article>
          <h2>{
   
   { item.title }}</h2>
          <p>{
   
   { item.body }}</p>
        </article>
      </div>
    </template>
    <template #fallback>
      Articles loading...
    </template>
  </Suspense>
</template>
<script>
import axios from 'axios'
export default {
  async setup() {
    let articleList = await axios
      .get('https://jsonplaceholder.typicode.com/posts')
      .then(response => {
        console.log(response)
        return response.data
      })
    return {
      articleList
    }
  }
}
</script>
复制代码

4、Multiple v-models

We all know that v-modelsfor two-way data binding. Generally used with form elements. Sometimes we will use it in custom components.

Vue 2Only one is allowed on one component v-models. In the Vue 3middle, we can be any number of v-modelbound to our custom components:

<template>
  <survey-form v-model:name="name" v-model:age="age">
    {" "}
  </survey-form>
</template>
复制代码

SurveyForm.vue:

<template>
    <div>
        <label>Name: </label>
        <input :value="name" @input="updateName($event.target.value)" />
        <label>Age: </label>
        <input :value="age" @input="updateAge($event.target.value)" />
    </div>
</template>
<script>
    export default {
      props: {
        name: String,
        age: Number
      },
      setup(props, { emit }) {
        const updateName = value => {
          emit('update:name', value)
        }
        const updateAge = value => {
          emit('update:age', +value)
        }
        return { updateName, updateAge }
      }
    }
</script>
复制代码

5、Reactivity

Vue 2 The responsiveness of is already great, but in a few cases there will be some problems:

<template>
  <div class="hello" @click="test">test {
   
   {list }} {
   
   { myObj }}</div>
</template>
<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      list: [1, 2],
      myObj: { name: "Preetish" }
    };
  },
  watch: {
    list: {
      handler: () => {
        console.log("watcher triggered");
      },
      deep: true
    }
  },
  methods: {
    test() {
      this.list[2] = 4;
      this.myObj.last = "HS";
      delete this.myObj.name;
    }
  }
};
</script>
复制代码

We found that by this.listmodifying the elements index, and will not trigger wacherthe listener function, in order to achieve their goals, we have to use vue.set()or vue.delete()these methods.

In the vue 3middle, we do not need the aid of other API:

export default {
  setup() {
    let list = ref([1, 2]);
    let myObj = ref({ name: "Preetish" });
    function myFun() {
      list.value[3] = 3;
      myObj.value.last = "HS";
      delete myObj.value.name;
    }
    return { myFun, list, myObj };
  },
};
复制代码

6、Portals

PortalsIt provided a component to render a page in any DOMcapacity nodes. In Vue 2utilizing a portal-vuethird-party plug-in to do this.

In the vue 3direct use:

<Teleport to="#modal-layer">
  <div class="modal">hello</div>
</Teleport>
复制代码

<Teleport> is a specific tag provided in vue3 to create one Portals.

<Teleport> SUMMARY </ Teleport> will appear in the intermediate todesignated node:

<div id="modal-target"></div>
复制代码

So far, <Teleport> is not available in the Alpha version

7、Transition

Before I use v-enter-active, v-enter, v-enter-toengage in confusing these states.

Now Vue 3 is more intuitive in terms of naming: v-enterbecome v-enter-from, v-leavebecome v-leave-from.

8、Remove Filter

Vue 3Abandoned Filterusage, property or more recommended calculation methods to achieve:

<!-- vue 2.x -->
{
   
   { date | format }}

<!-- vue 3.0 -->
{
   
   { format(date) }}
复制代码

9、App configration

In Vue 2, if you want to use the use(), mixin(), directive()and other methods need to meet the global Vuetarget:

import Vue from "vue";
import App from "./App";

Vue.use(/* ... */);
Vue.mixin(/* ... */);
Vue.component(/* ... */);
Vue.directive(/* ... */);

new Vue({
  el: "#app",
  template: "<App/>",
  components: {
    App,
  },
});
复制代码

In Vue 3, the changed createAppreturn VueExample:

import { createApp } from "vue";
import App from "./App.vue";

const app = createApp(App);

app.use(/* ... */);
app.mixin(/* ... */);
app.component(/* ... */);
app.directive(/* ... */);

app.mount("#app");
复制代码

Concluding remarks

In short Vue 3to organize and share code by providing a simple way, and provide a strong TypeScriptsupport for the new code organization will have a significant impact on the future of application development.

Meanwhile, some other features, such as Suspense, more v-modelsetc. will bring great convenience to developers.

At the same time, the performance is faster and the size is smaller. How it is done, please refer to another article: Vue.js Author: stories about the behind Vue3.0



Link: https://juejin.im/post/6844904162799386632
Source: Nuggets
 

Guess you like

Origin blog.csdn.net/weixin_44273311/article/details/108074369