1.创建项目
vue create vuetest
npm run serve ---启动
2.项目压缩配置
compression-webpack-plugin:插件能够通过压缩算法,将前端打包好的资源文件进一步压缩,生成指定的、体积更小的压缩文件,让浏览器能够更快的加载资源
const CompressionPlugin = require('compression-webpack-plugin');
const productionGzipExtensions = ['js', 'css','ts'];
configureWebpack: config=> {
// 开启Gzip压缩
// if (isProduction) {
config.plugins.push(
new CompressionPlugin({
algorithm: 'gzip',
test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
threshold: 500,
minRatio: 0.8
})
);
}
3.响应式 API:核心
1.ref()
<template>
<div class="home">
{{count}}
<button @click="add">加</button>
</div>
</template>
<script lang="ts" setup>
import { ref } from 'vue';
const count = ref(0)
const add = () => {
count.value++
}
</script>
2.computed ()
<template>
<div class="home">
{{count}}
<button @click="add">加</button>
<div>computed:{{plusOne}}</div>
</div>
</template>
<script lang="ts" setup>
import { ref, computed } from 'vue';
const count = ref(0)
const add = () => {
count.value++
}
// 写法1
// const plusOne = computed(() => count.value + 3)
// 写法2
const plusOne = computed({
get: () => count.value + 1,
set: (val) => {
count.value = val - 1
}
})
plusOne.value = 1
console.log('count',count.value) // 0
</script>
3.reactive()
返回一个对象的响应式代理。
<template>
<div class="home">
{{obj.count}}
<button @click="add">加</button>
</div>
</template>
<script lang="ts" setup>
import { reactive } from 'vue';
const obj = reactive({ count: 0 })
const add = () => {
obj.count++
}
</script>
4.watchEffect() 监听
<template>
<div class="home">
{{obj.count}}
<button @click="add">加</button>
<div>watchEffect:{{watchValue}}</div>
</div>
</template>
<script lang="ts" setup>
// 立即运行一个函数,同时响应式地追踪其依赖,并在依赖更改时重新执行。如果有多个属性同时更新,这将导致一些性能和数据一致性的问题
import { reactive, ref, watchEffect } from 'vue';
const obj = reactive({ count: 0 })
const add = () => {
obj.count++
}
const watchValue = ref(0)
watchEffect(() => {
// 用来做响应性追踪
watchValue.value = obj.count
})
</script>
5.watch()
<template>
<div class="home">
{{obj.count}}
<button @click="add">加</button>
<div>watchNewValue:{{watchNewValue}}</div>
<div>watchOldValue:{{watchOldValue}}</div>
</div>
</template>
<script lang="ts" setup>
import { reactive, ref, watch } from 'vue';
const obj = reactive({ count: 0 })
const add = () => {
obj.count++
}
const watchNewValue = ref(0)
const watchOldValue = ref(0)
watch(() => obj.count, (count, prevCount) => {
watchNewValue.value = count
watchOldValue.value = prevCount
})
</script>