vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > vue3 nextTick和historyApiFallback

vue3深入学习 nextTick和historyApiFallback

作者:满山前端我头最秃​​​​​​​

这篇文章主要介绍了vue3深入学习 nextTick和historyApiFallback,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的朋友可以参考一下

1、nextTick

 官方解释:将回调推迟到下一个 DOM 更新周期之后执行。在更改了一些数据以等待 DOM 更新后立即使用它。

比如我们有下面的需求:

<template>
  <div>
    <h3 class="title" ref="title">{{ message }}</h3>
    <button @click="handleClick">添加内容</button>
  </div>
</template>
<script setup>
import { ref } from 'vue'
const message = ref('')
const title = ref(null)

const handleClick = () => {
  message.value += 'NextTick!'
  console.log(title.value.offsetHeight)
}
</script>

<style scoped>
.title {
  width: 100px;
  word-break: break-all;
}
</style>

可以看到,上面每次打印的都是上一次元素内容的高度

实现上面的案例我们有三种方式:

<template>
  <div>
    <h3 class="title" ref="title">{{ message }}</h3>
    <button @click="handleClick">添加内容</button>
  </div>
</template>

<script setup>
import { ref, onUpdated } from 'vue'

const message = ref('')
const title = ref(null)

const handleClick = () => {
  message.value += 'NextTick!'
}

onUpdated(() => {
  console.log(title.value.offsetHeight)
})
</script>

<style scoped>
.title {
  width: 100px;
  word-break: break-all;
}
</style>

方式三: 使用nextTick函数;

nextTick是如何做到的呢?

<template>
  <div>
    <h3 class="title" ref="title">{{ message }}</h3>
    <button @click="handleClick">添加内容</button>
  </div>
</template>
<script setup>
import { ref, nextTick } from 'vue'

const message = ref('')
const title = ref(null)

const handleClick = () => {
  message.value += 'NextTick!'

  // 更新 DOM
  nextTick(() => {
    console.log(title.value.offsetHeight)
  })
}
</script>

<style scoped>
.title {
  width: 100px;
  word-break: break-all;
}
</style>

2、historyApiFallback

1.historyApiFallback是开发中一个非常常见的属性,它主要的作用是解决SPA页面在路由跳转之后,进行页面刷新时,返回404的错误。

2.boolean值:默认是false

3.object类型的值,可以配置rewrites属性:

4.事实上devServer中实现historyApiFallback功能是通过connect-history-api-fallback库的:

可以查看文档

代码在vue-cli脚手架项目的node_modules/@vue/cli-service/lib/commands/serve.js中:

const server = new WebpackDevServer(compiler, Object.assign({
  historyApiFallback: {
    disableDotRule: true
  }
}))

现在已经是vite打包工具了,上面是webpack的配置

自己配置可以在项目根目录下创建一个vue.config.js文件,在这个文件中进行配置:

module.exports = {
  configureWebpack: {
    devServer: {
      historyApiFallback: true
    }
  }
}

到此这篇关于vue3深入学习 nextTick和historyApiFallback的文章就介绍到这了,更多相关vue3 nextTick和historyApiFallback内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文