vue3-setup-basic use

Summary

This article introduces how to start writing the first vue3 program and compares the difference with vue2. And introduce the basic use of very important setup in vue3. You need to have vue foundation.

content

  1. The first vue3 program, revisiting the classic two-way binding

  2. Understanding setup configuration items

  3. setup defines responsive data (ref single value)

  4. setup defines reactive data (reactive object)

  5. setup defines reactive data (reactive object + toRefs)

  6. setup defines calculation properties

  7. setup defines watch

  8. setup defines life cycle hook function

  9. summary

The first vue3 program

Learn to write the first vue3 program and feel the smooth transition from vue2 to vue3.

<script src="https://unpkg.com/vue@next"></script> <body>   <div id="app">     <h3>经典的双向绑定</h3>     <input v-model.trim="msg" />     <div>        {
   
   {msg}}     </div>   </div>   <script>     const { createApp } = Vue     const app = createApp({
   
          data() {
   
             return{
   
               msg: 'hello vue3'          }       }       // 正常写其它配置,methods,computed...      })    // 每一个vue应用从创建应用实例开始。    // 1. app是应用实例    // 可以在app上封装应用级别的组件,过滤器,指令    // app.component('SearchInput', SearchInputComponent)    // app.directive('focus', FocusDirective)    // app.use(LocalePlugin)    // 2. vm是根组件,当挂载整个应用时,它是渲染的起点。    // 定义在data中的属性,将通过vm暴露出来    const vm = app.mount("#app")    // vm.msg = '你好,vue3'</script> </body></html> 

Precautions:

  1. app is the application instance and vm is the root component.

  2. The function of app.mount() is to hang the Vue application instance into the specified dom container. Its return value is the root component of the entire application. You can access the data through vm.msg, or modify the data to reflect the responsiveness effect.

  3. The parameter of the createApp() function is an object, which is the configuration item of the root component:

  • data must be written in the return value of the function,

  • If the template is set in the configuration item, the rendered content will be based on the template.

Understanding setup configuration items

The setup configuration item has been added to vue3. Use it to write combined api. Now let's get to know it briefly. ​​​​​​​

<script src="https://unpkg.com/vue@next"></script><body> <div id="app">   <h3>setup</h3>   {
   
   {a}} - {
   
   {b}}   <button @click="f">f函数</button> </div> <script>   const { createApp } = Vue   const app = createApp({
   
        data() {
   
           return {
   
             a: 1        }     },     setup() {
   
         console.log('setup ....')      return {b: 2, f: function(){console.log('f')}}     },     created() {
   
         console.log('created ....')      console.log(this.a)      console.log(this.b)      setTimeout(()=>this.b=100, 2000)      this.f()     }    })   app.mount("#app")</script></body>

Key points:

  1. This hook will be executed before created

  2. There is no this inside

  3. If its return value is an object, the key-value pairs in this object will eventually be merged into this in the created hook, so that the corresponding data value can also be accessed on the view (for example, b and function f in the code above) )

  4. Without special processing, its data will not have a responsive effect: you modify the value of b, and it will not cause the view to update.

Setup defines responsive data (ref single value)

We can get a data with responsive effect through Vue.ref (basic data), and then return it through setup. ​​​​​​​

 <script src="https://unpkg.com/vue@next"></script> <body>   <div id="app">     <h3>setup-ref响应式</h3>     <p>希望这里返回的b是响应式的</p>     a:{
   
   {a}} - b: {
   
   {b}}     <button @click="f">f</button>     <button @click="f1">f1</button>   </div>   <script>     const { createApp, ref } = Vue     const app = createApp({
   
          data() {
   
             return {
   
               a: 1          }       },       setup() {
   
           // 希望这里返回的b是响应式的:改了b的值,页面也会更新        // ref: 会对基础数据进行包装        // 它其实是用proxy代理了一个对象  `{ value: 0 }`        const b = ref(0)        const f1 = () => { b.value = 200}        return { b , f1  }       },       methods: {
   
            f () {
   
              // 这里不能写this.b.value           this.b = 100         }       }      })     app.mount("#app")</script>

If you want to return data with responsive effects in setup, you can use the ref function to process the data. Specific steps:

  1. Return a ref() processed data in setup

  2. Normally use interpolation { {b}} in the view (no need to add .value)

  3. If you want to modify this value, there are two ways:

    1) Expose a function in setup and modify .value directly

    2) Define a method in methods, and modify this.XX=new value inside this method

setup defines reactive data (reactive object)

We can get an object with responsive effect through Vue.reactive (object), and then return it through setup. ​​​​​​​

<script src="https://unpkg.com/vue@next"></script> <body>   <div id="app">     <h3>setup-reactive响应式</h3>     <p>希望这里返回的复合数据-obj是响应式的</p>    obj.b: {
   
   {obj.b}},  obj.arr:{
   
   {obj.arr}}     <button @click="f">f</button>     <button @click="f1">f1</button>     <button @click="f2">f2</button>   </div>   <script>   const { createApp, reactive } = Vue   const app = createApp({
   
        data() {
   
           return {
   
           }     },     setup() {
   
         // reactive: 会对对象进行包装      const obj = reactive({b: 1, arr: [1,2]})      const f1 = () => { obj.b = 200 }      const f2 = () => { obj.arr.push(3)}      return { obj, f1, f2  }     },     methods: {
   
          f () {
   
            this.obj.b = 100       }     }    })   app.mount("#app")</script></body>

step:

  1. Return a reactive() processed object obj in setup

  2. Interpolation is normally used in the view, but obj is added.

  3. If you want to modify this value, there are two ways:

    1) Expose a function in setup and modify it directly 

    2) Define a method in methods and modify it internally by this.ojb.XX=new value

setup returns reactive data (reactive object + toRefs)

In the above example, we need to use { {obj.b}} to render data in the view. Let's optimize it. By introducing toRefs to wrap this object, and then expand it, we can omit the obj prefix. ​​​​​​​

<script src="https://unpkg.com/vue@next"></script> <body>   <div id="app">     <h3>setup-ref响应式</h3>     <p>希望这里返回的复合数据-obj是响应式的</p>    obj.b: {
   
   {b}},  obj.arr:{
   
   {arr}}     <button @click="f">f</button>     <button @click="f1">f1</button>     <button @click="f2">f2</button>   </div>   <script>    // vue3中提供一个概念:组合api     const { createApp, reactive, toRefs } = Vue     const app = createApp({
   
          data() {
   
             return {
   
             }       },      //  步骤:      //  1. 在setup中返回一个reactive()处理的对象obj      //  2. 在视图中正常用插值,但是要加上obj.      //  3. 如果要修改这个值,有两种方式:      //   1) 在setup中暴露一个函数,直接去修改      //   2) 在methods中定义一个方法,在内部通过this.XX=新值来修改       setup() {
   
           // reactive: 会对对象进行包装        // 它其实是用proxy代理了这个对象,只是第一个级别,所以不能直接解构        // 如果直接解构,就失去了响应式的特性了        // 这里再用toRefs来包装一下        const obj = reactive({b: 1, arr: [1,2]})        const f1 = () => { obj.b = 200}        const f2 = () => { obj.arr.push(3)}        return { ...toRefs(obj), f1, f2  }       },       methods: {
   
            f () {
   
              this.b = 100         }       }      })     app.mount("#app")</script></body>

The core code is: return { ...toRefs(obj) , f1, f2}

setup defines calculation properties

<script src="https://unpkg.com/vue@next"></script> <body>   <div id="app">      <h3>setup-computed计算属性</h3>      obj.b: {
   
   {obj.b}}      <br>      <p>计算属性:2倍:{
   
   {doubleB}} </p>      <p>计算属性:0.5倍:{
   
   {halfB}} </p>      <p>计算属性:3倍:{
   
   {triangleB}} </p>      <button @click="obj.b+=1">原值+1</button>   </div>   <script>   const { createApp, reactive, computed } = Vue   const app = createApp({
   
        data() {
   
           return {}     },    //  步骤:    //  1. 在setup中通过computed来创建函数,    //  2. 导出     setup() {
   
         // reactive: 会对对象进行包装      const obj = reactive({b: 1})      // 通过computed来创建计算属性      const doubleB = computed(()=>{
   
           return 2*obj.b      })      const triangleB = computed(()=>{
   
           return 3*obj.b      })      return { obj, doubleB, triangleB }     },     computed: {
   
          halfB () {
   
            return this.obj.b / 2       }     }    })   app.mount("#app")</script></body>

Calculate the properties by computed (callback), and then return in setup.

Write watch in setup​​​​​​​

<script src="https://unpkg.com/vue@next"></script>

   <div id="app">      <h3>setup-watch</h3>      {
   
   {obj.b}}, {
   
   {a}}      <br>      <button @click="obj.b+=1">原值b+1</button>      <button @click="a+=1">原值a+1</button>   </div>   <script>   const { createApp, reactive, watch, ref } = Vue   const app = createApp({
   
        data() {
   
           return {
   
           }     },     setup() {
   
         // reactive: 会对对象进行包装      const obj = reactive({b: 1})      const a = ref(0)      // 通过watch来监听      watch(() => obj.b ,()=>{
   
           console.log(`obj.b变化了`)      })      watch(a, ()=>{
   
           console.log(`a变化了`)      })      return { obj, a }     }    })   app.mount("#app")</script>

Write hook function in setup​​​​​​​

<script src="https://unpkg.com/vue@next"></script><body> <div id="app">    <h3>setup-钩子函数</h3> </div> <script>   const { createApp,onMounted} = Vue   const app = createApp({
   
        data() {
   
           return {
   
           }     },     setup() {
   
         onMounted(()=>{ console.log('setup, mounted1')})      onMounted(()=>{ console.log('setup, mounted2')})     },     mounted () {
   
          console.log('mounted')     }    })   app.mount("#app")</script>

The above code only demonstrates mounted, and other hooks are similar.

summary

This article introduces how to start writing the first program of vue3, learn to use createApp to create an instance, use mount to mount the instance to dom, and use ref, reactive, toRef, computd, watch, onMounted and other apis in setup. Compare the effects in vue2, hope it will help you.

 

This article is just some grammar introduction, in the next article I will introduce two specific functions of setup.

If it helps you, I suggest you choose at least one of the following actions image:

Guess you like

Origin blog.csdn.net/sqLeiQ/article/details/111310796