Home  >  Article  >  Web Front-end  >  Knowledge points gained using Vue3.0 (2)

Knowledge points gained using Vue3.0 (2)

coldplay.xixi
coldplay.xixiforward
2020-09-19 09:26:112400browse

Knowledge points gained using Vue3.0 (2)

# I work overtime every day and I am busy every day, and the demand comes like a tiger or a wolf. The test questions piled up like a mountain, and I returned home disappointed.

Related learning recommendations: javascript

Recently, I have been studying Vue3.0 related knowledge after work , although Vue3.0 is still the rc version, this does not affect our study. Today's article is my fourth article about Vue3.0. In the previous article, we explained how to build the Vue3.0 development environment through vite and vuecli, and then introduced the Vue3.0 setup,reactive,ref, etc. Today’s article mainly explains the following content:

  1. Vue3.0 Used in watch
  2. Vue3.0 Used in computed properties
  3. Vue3.0 Used in vue-router
  4. Used in Vue3.0vuex

Before starting this article, the editor provides A Vue3.0 development environment has been created. The warehouse address is gitee.com/f_zijun/vue…. Welcome to use it. This article was first published on the public account [Front-end Youdewan], which is a public account focusing on Vue and Interview. To improve your market competitiveness, just in [Front-end Youde] Play】. At the same time, click the following link to access the editor's other related articles about Vue3.0

To learn Vue3.0, let's first learn about Proxy

Usagevite Build a Vue3.0 learning environment

Knowledge points gained using Vue3.0 (1)

## The use of watch

watch

in #Vue3.0 is not a new concept in Vue3.0. When using # When ##Vue2.x, we often use watch to monitor changes in an expression or a function calculation result on the Vue instance. Review

watch

In Vue2.0, we use

watch

You can monitor changes in expressions or function calculation results on the Vue instance through the following multiple methods. The following is a list of several of themThe most common Usage

export default {
  data() {    return {      name: '子君',      info: {        gzh: '前端有的玩'
      }
    }
  },  watch: {
    name(newValue, oldValue) {      console.log(newValue, oldValue)
    },    'info.gzh': {
      handler(newValue, oldValue) {        console.log(newValue, oldValue)
      },      // 配置immediate会在watch之后立即执行
      immediate: true
    }
  }
}复制代码
    We can configure the properties on the
  1. Vue

    instance to be monitored in the

    watch

    property, or we can go through the . key path Monitoring changes in a certain attribute in the object can also be triggered immediately after monitoring by configuring immediate, and configuring deep to deeply monitor the properties in the object, no matter how deep the nesting level is. . Use

    $watch
  2. to monitor
  3. In addition to the conventional watch object writing method,

    Vue

    The $watch method is provided on the instance, which can be used to more flexibly monitor changes in a certain attribute. For example, in this scenario, we have a form, and we hope to monitor the data changes in the form after the user modifies the form. But there is a special scenario, that is, the backfill data of the form is requested asynchronously. At this time, we hope to monitor the changes after requesting the data in the background. In this case, we can use $watch. As shown in the following code: <pre class="brush:js;toolbar:false;">export default { methods: { loadData() { fetch().then(data =&gt; { this.formData = data this.$watch( &amp;#39;formData&amp;#39;, () =&gt; { // formData数据发生变化后会进入此回调函数 }, { deep: true } ) }) } } }复制代码</pre>Listening function expressionIn addition to the listening string, the first parameter of

    $watch
  4. can also be It is a function. When the return value of the function changes, the callback function is triggered
  5. this.$watch(() => this.name, () => {  // 函数的返回值发生变化,进入此回调函数})复制代码

    The above are some common writing methods we use

    watch

    in Vue2.0, For

    Vue3.0

    , because it is partially backward compatible with Vue2.0, the above usage can basically be used in Vue3.0 , but a big highlight of Vue3.0 is the composition API, so in addition to the writing method in Vue2.0, you can also use componsition watch provided in api is used in Vue3.0

    watch

In Vue3.0, in addition to the writing method of Vue2.0, there are two

api

that can monitor data changes. The first one iswatch, the second one is watchEffect. For watch, its usage is basically the same as $watch in Vue2.0, while watchEffect is Vue3. 0Newly providedapiUsage of watchThe following example demonstrates how to use watch

import { watch, ref, reactive } from &#39;vue&#39;export default {
  setup() {    const name = ref(&#39;子君&#39;)    const otherName = reactive({      firstName: &#39;王&#39;,      lastName: &#39;二狗&#39;
    })
    watch(name, (newValue, oldValue) => {      // 输出 前端有的玩 子君
      console.log(newValue, oldValue)
    })    // watch 可以监听一个函数的返回值
    watch(      () => {        return otherName.firstName + otherName.lastName
      },
      value => {        // 当otherName中的 firstName或者lastName发生变化时,都会进入这个函数
        console.log(`我叫${value}`)
      }
    )

    setTimeout(() => {
      name.value = &#39;前端有的玩&#39;
      otherName.firstName = &#39;李&#39;
    }, 3000)
  }
}复制代码
watch

In addition to monitoring a single value or function return value, you can also monitor multiple data sources at the same time, as shown in the following code:<pre class="brush:js;toolbar:false;">export default { setup() { const name = ref(&amp;#39;子君&amp;#39;) const gzh = ref(&amp;#39;前端有的玩&amp;#39;) watch([name, gzh], ([name, gzh], [prevName, prevGzh]) =&gt; { console.log(prevName, name) console.log(prevGzh, gzh) }) setTimeout(() =&gt; { name.value = &amp;#39;前端有的玩&amp;#39; gzh.value = &amp;#39;关注我,一起玩前端&amp;#39; }, 3000) } }复制代码</pre><h5 data-id="heading-4">watchEffect的用法</h5> <p><code>watchEffect的用法与watch有所不同,watchEffect会传入一个函数,然后立即执行这个函数,对于函数里面的响应式依赖会进行监听,然后当依赖发生变化时,会重新调用传入的函数,如下代码所示:

import { ref, watchEffect } from &#39;vue&#39;export default {
  setup() {    const id = ref(&#39;0&#39;)
    watchEffect(() => {      // 先输出 0 然后两秒后输出 1
      console.log(id.value)
    })

    setTimeout(() => {
      id.value = &#39;1&#39;
    }, 2000)
  }
}复制代码
  1. 停止执行

    Vue2.0中的$watch会在调用的时候返回一个函数,执行这个函数可以停止watch,如下代码所示

    const unwatch = this.$watch(&#39;name&#39;,() => {})// 两秒后停止监听setTimeout(()=> {
      unwatch()
    }, 2000)复制代码

    Vue3.0中,watchwatchEffect同样也会返回一个unwatch函数,用于取消执行,比如下面代码所示

    export default {
      setup() {    const id = ref(&#39;0&#39;)    const unwatch = watchEffect(() => {      // 仅仅输出0
          console.log(id.value)
        })
    
        setTimeout(() => {
          id.value = &#39;1&#39;
        }, 2000)    // 1秒后取消watch,所以上面的代码只会输出0
        setTimeout(() => {
          unwatch()
        }, 1000)
      }
    }复制代码
    1. 清除副作用

      想象一下这样的一个场景,界面上面有两个下拉框,第二个下拉框的数据是根据第一个下拉框的数据联动的,当第一个下拉框数据发生变化后,第二个下拉框的数据会通过发送一个网络请求进行获取。这时候我们可以通过watchEffect来实现这个功能,比如像下面代码这样

      import { ref, watchEffect } from &#39;vue&#39;function loadData(id) {  return new Promise(resolve => {
          setTimeout(() => {
            resolve(        new Array(10).fill(0).map(() => {          return id.value + Math.random()
              })
            )
          }, 2000)
        })
      }export default {
        setup() {    // 下拉框1 选中的数据
          const select1Id = ref(0)    // 下拉框2的数据
          const select2List = ref([])
          watchEffect(() => {      // 模拟请求
            loadData(select1Id).then(data => {
              select2List.value = data        console.log(data)
            })
          })    
          // 模拟数据发生变化
          setInterval(() => {
            select1Id.value = 1
          }, 3000)
        }
      }复制代码

      现在假如我切换了一下第一个下拉框的数据之后,这时候数据请求已经发出,然后我将这个页面切换到另一个页面,因为请求已经发出,所以我希望在页面离开的时候,可以结束这个请求,防止数据返回后出现异常,这时候就可以使用watchEffect为第一个回调函数传入的入参来处理这个情况,如下代码所示

      function loadData(id, cb) {  return new Promise(resolve => {    const timer = setTimeout(() => {
            resolve(        new Array(10).fill(0).map(() => {          return id.value + Math.random()
              })
            )
          }, 2000)
          cb(() => {
            clearTimeout(timer)
          })
        })
      }export default {
        setup() {    // 下拉框1 选中的数据
          const select1Id = ref(0)    // 下拉框2的数据
          const select2List = ref([])
          watchEffect(onInvalidate => {      // 模拟请求
            let cancel = undefined
            // 第一个参数是一个回调函数,用于模拟取消请求,关于取消请求,可以了解axios的CancelToken
            loadData(select1Id, cb => {
              cancel = cb
            }).then(data => {
              select2List.value = data        console.log(data)
            })
            onInvalidate(() => {
              cancel && cancel()
            })
          })
        }
      }复制代码

Vue3.0中使用计算属性

想一想在Vue2.0中我们一般会用计算属性做什么操作呢?我想最常见的就是当模板中有一个复杂计算的时候,可以先使用计算属性进行计算,然后再在模板中使用,实际上,Vue3.0中的计算属性的作用和Vue2.0的作用基本是一样的。

  1. Vue2.0中使用计算属性

      computed: {
        getName() {      const { firstName, lastName } = this.info      return firstName + lastName
        }
      },复制代码
  1. Vue3.0中使用计算属性

    <template>  <p class="about">
        <h1>{{ name }}</h1>
      </p></template>
    <script>
    import { computed, reactive } from &#39;vue&#39;
    
    export default {
      setup() {
        const info = reactive({
          firstName: &#39;王&#39;,
          lastName: &#39;二狗&#39;
        })
    
        const name = computed(() => info.firstName + info.lastName)
    
        return {
          name
        }
      }
    }
    </script>复制代码

    Vue2.0一样,Vue3.0的计算属性也可以设置gettersetter,比如上面代码中的计算属性,只设置了getter,即加入cumputed传入的参数是一个函数,那么这个就是getter,假如要设置setter,需要像下面这样去写

    export default {
      setup() {    const info = reactive({      firstName: &#39;王&#39;,      lastName: &#39;二狗&#39;
        })    const name = computed({      get: () => info.firstName + &#39;-&#39; + info.lastName,
          set(val) {        const names = val.split(&#39;-&#39;)
            info.firstName = names[0]
            info.lastName = names[1]
          }
        })    return {
          name
        }
      }
    }复制代码

Vue3.0中使用vue-router

初始化vue-router

Vue2.0中我们使用vue-router的时候,会通过new VueRouter的方式去实现一个VueRouter实例,就像下面代码这样

import Vue from &#39;vue&#39;import VueRouter from &#39;vue-router&#39;Vue.use(VueRouter)const router = new VueRouter({  mode: &#39;history&#39;,  routes: []
})export default router复制代码

但到了Vue3.0,我们创建VueRouter的实例发生了一点点变化,就像Vue3.0main.js中初始化Vue实例需要像下面写法一样

import { createApp } from &#39;vue&#39;createApp(App).$mount(&#39;#app&#39;)复制代码

vue-router也修改为了这种函数的声明方式

import { createRouter, createWebHashHistory } from &#39;vue-router&#39;const router = createRouter({  // vue-router有hash和history两种路由模式,可以通过createWebHashHistory和createWebHistory来指定
  history: createWebHashHistory(),
  routes
})

router.beforeEach(() => {
  
})

router.afterEach(() => {
  
})export default router复制代码

然后在main.js中,通过

 createApp(App).use(router)复制代码

来引用到Vue

setup中使用vue-router

Vue2.0中,我们通过this.$route可以获取到当前的路由,然后通过this.$router来获取到路由实例来进行路由跳转,但是在setup中,我们是无法拿到this的,这也意味着我们不能像Vue2.0那样去使用vue-router, 此时就需要像下面这样去使用

import { useRoute, useRouter } from &#39;vue-router&#39;export default {
  setup() {    // 获取当前路由
    const route = useRoute()    // 获取路由实例
    const router = useRouter()    // 当当前路由发生变化时,调用回调函数
    watch(() => route, () => {      // 回调函数
    }, {      immediate: true,      deep: true
    })    
    // 路由跳转
    function getHome() {
      router.push({        path: &#39;/home&#39;
      })
    }    
    return {
      getHome()
    }
  }
}复制代码

上面代码我们使用watch来监听路由是否发生变化,除了watch之外,我们也可以使用vue-router提供的生命周期函数

import { onBeforeRouteUpdate, useRoute } from &#39;vue-router&#39;export default {
  setup() {
    onBeforeRouteUpdate(() => {      // 当当前路由发生变化时,调用回调函数
    })
  }
}复制代码

除了onBeforeRouteUpdate之外,vue-router在路由离开的时候也提供了一个生命周期钩子函数

onBeforeRouteLeave(() => {   console.log(&#39;当当前页面路由离开的时候调用&#39;)
})复制代码

Vue3.0中使用vuex

其实vuexVue3.0中的使用方式和vue-router基本是一致的

初始化vuex

首先新建store/index.js,然后添加如下代码

import { createStore } from &#39;vuex&#39;export default createStore({  state: {},  mutations: {},  actions: {}
})复制代码

然后在main.js中,通过以下方式使用

 createApp(App).use(store)复制代码

setup中使用vuex

useRouter一样,vuex也提供了useStore供调用时使用,比如下面这段代码

import { useStore } from &#39;vuex&#39;export default {
  setup() {
    const store = useStore()
    const roleMenus = store.getters[&#39;roleMenus&#39;]
    return {
      roleMenus
    }
  }
}复制代码

其余的使用方式基本和Vue2.0中的用法是一致的,大家具体可以参考vuex官方文档

Vue3.0中的生命周期钩子函数

在前文中,我们说到Vue3.0是兼容一部分Vue2.0的,所以对于Vue2.0的组件写法,生命周期钩子函数并未发生变化,但是假如你使用的是componsition api,那么就需要做一部分调整

  1. 取消beforeCreatecreated

    在使用componsition api的时候,其实setup就代替了beforeCreatecreated,因为setup就是组件的实际入口函数。

  2. beforeDestroydestroyed 改名了

    setup中,beforeDestroy更名为onBeforeUnmount,destroyed更名为onUnmounted

  3. 将生命周期函数名称变为on+XXX,比如mounted变成了onMounted,updated变成了onUpdated

setup中使用生命周期函数的方式

setup() {
    onMounted(() => {      console.log(&#39;mounted!&#39;)
    })
    onUpdated(() => {      console.log(&#39;updated!&#39;)
    })
    onUnmounted(() => {      console.log(&#39;unmounted!&#39;)
    })
  }复制代码

实际用法与Vue2.0基本是一致的,只是写法发生了变化,所以学习成本是很低的。

总结

这是小编关于Vue3.0的第四篇文章,每一篇文章都是自己在学习中做的一些总结。小编整理了一个vue3.0的开发环境,仓库地址为 gitee.com/f_zijun/vue…,内部集成了typescript,eslint,vue-router,vuex,ant desigin vue等,希望可以帮到正在学习Vue3.0的你,同时关注公众号【前端有的玩】,带给你不一样的惊喜。喜欢本文,可以给小编一个赞哦。

结语

不要吹灭你的灵感和你的想象力; 不要成为你的模型的奴隶。 ——文森特・梵高

The above is the detailed content of Knowledge points gained using Vue3.0 (2). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.im. If there is any infringement, please contact admin@php.cn delete
Previous article:Meet ajaxNext article:Meet ajax