1.ref使用
vue2 中我们使用 this.$refs.barChart
来访问,但是vue3发现不好使了,在setup语法糖之前,我们还可以通过 content.refs.barChart
来访问,尤大神升级之后发现蒙了,不知道怎么使用了,其实也很简单,就是使用ref来实现.
<template>
<div ref="barChart" :style="[{ height: height, width: width }]"></div>
</template>
<script setup>
const barChart = ref();
console.log(barChart.value) // undefined
onMounted(() => {
console.log(barChart.value); // Proxy
});
</script>
使用setup语法糖获取ref需要注意,ref()定义的变量名称必须合上面div的ref的值一致。
如果需要获取子组件的属性或方法,需要使用 defineExpose
方法将需要调用的属性或方法暴露出来。
<script setup>
// 子组件
const resetMasonry = () => console.log(111)
defineExpose({
resetMasonry,
});
</script>
// 父组件
<script setup>
import { ref, onMounted } from "vue";
const contList = ref();
onMounted(() => {
contList.value.resetMasonry()
});
</script>
2.子组件获取props
vue2获取
export default {
props: {
height: String,
},
created() {
console.log(this.height);
},
};
vue3获取
export default {
props: {
height: String,
},
setup(props, content) {
console.log(props.height);
},
};
vue3 setup语法糖
获取
<script setup>
const props = defineProps({
height: String
});
console.log(props.height)
</script>
vue3 setup语法糖 + ts
获取
<script lang="ts" setup>
import { ref } from "vue";
interface Props {
itemList?: any;
}
let props = withDefaults(defineProps<Props>(), {
itemList: [],
});
</script>
3.setup语法糖中使用ts定义变量
import { Ref, ref } from "vue";
// 数字
const page = ref(1);
const page: Ref<number> = ref(1);
// 字符串
const page: Ref<string> = ref('字符串');
// 数组
const list: Ref<number[]> = ref([1, 2, 3]);
emit使用
vue3 setup语法糖
获取
<script setup>
// 定义
const emit = defineEmits(['change', 'close']);
// 使用
const closeHandle = () => emit('close')
const changeHandle = (val) => emit('change', val)
</script>
setup语法糖中使用动态样式
<template>
<div :style="rootStyle.value">
{{ rootStyle }}
</div>
</template>
<script setup>
import { ref, computed } from "vue";
const rootStyle = ref(null);
rootStyle.value = computed(() => {
let { width, height } = props;
return {
"--width": width && width > 0 ? `${width}px` : "100%",
"--height": height && height > 0 ? `${height}px` : "100%",
};
});
</script>
需要注意:动态样式需要通过
xx.value
来调用。
vue3 子组件使用v-model
<template>
<input type="text" v-model="inputVal" />
</template>
<script setup>
import { computed } from "vue";
const props = defineProps({
fatherRef: string;
});
const emits = defineEmits(["changeVal"]);
const inputVal = computed({
get() {
return props.fatherRef;
},
set(val) {
emits("changeVal", val);
},
});
</script>
vue3 动态加载本地图片(解决reuqire不生效问题)
new URL("@/assets/images/data_center_sta_4.png", import.meta.url).href
// http://127.0.0.1:5900/src/assets/images/data_center_sta_4.png
vite.config.ts
import {
defineConfig
} from 'vite'
import vue from '@vitejs/plugin-vue'
const path = require("path")
export default defineConfig({
// 服务
server: {
// 服务器主机名
host: '0.0.0.0',
// 端口号
port: 3000,
// 设为 true 时若端口已被占用则会直接退出,
// 而不是尝试下移一格端口
strictPort: false,
// http.createServer() 配置项
// https: '',
proxy: {
'/api': {
target: 'http://...............',
changeOrigin: true,
rewrite: (path) => {
return path.replace(/^/api /, '')
}
}
},
// 开发服务器配置 CORS
// boolean | CorsOptions
cors: {},
// 设置为 true 强制使依赖构建
// force: true,
// 禁用或配置HMR连接
hmr: {},
// 传递给 chokidar 的文件系统监视器选项
watch: {}
},
// 项目根目录
// root: process.cwd(),
root: './src/',
// 项目部署的基础路径
base: '/',
// 环境配置
mode: 'development',
// 全局变量替换 Record<string, string>
define: {},
// 插件
plugins: [vue()],
// 静态资源服务文件夹
publicDir: 'public',
resolve: {
alias: {
'@': path.resolve(__dirname, 'src'),
'components': path.resolve(__dirname, 'src/components')
},
dedupe: [],
// 情景导出package.json 配置中的 exports 字段
conditions: [],
// 解析package.json 中的字段
mainFields: ['module', 'jsnext:main', 'jsnext'],
// 导入时想要省略的扩展名列表
extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue']
},
css: {
// 配置css modules 的行为, 选项被传递给postcss-modules
modules: {},
// PostCSS 配置(格式同postcss.config.js)
// postcss-load-config 的插件配置
postcss: {},
// 指定传递给 CSS 预处理器的选项
preprocessorOptions: {
}
},
json: {
// 是否支持从 .json 文件中进行按名导入
namedExports: true,
// 若设置为 true, 导入的 JSON 会被转换为 export default JSON.parse("...") 会比转译成对象字面量性能更好
// 尤其是当 JSON 文件较大时
// 开启此项, 则会禁用按名导入
stringify: false
},
// 继承自 esbuild 转换选项, 最常见的用例是自定义 JSX
esbuild: {
jsxFactory: 'h',
jsxFragment: 'Fragment',
jsxInject: `import React from 'react'`
},
// 静态资源处理 字符串 || 正则表达式
assetsInclude: '',
// 调整控制台输出的级别 'info' | 'warn' | 'error' | 'silent'
logLevel: 'info',
// 设为 false 可以避免 Vite 清屏而错过在终端中打印某些关键信息
clearScreen: true,
build: {
// 浏览器兼容性 ‘esnext’ | 'modules'
target: 'modules',
//输出路径
outDir: '../dist',
// 生成静态资源的存放路径
assetsDir: '../assets',
// 小于此阈值的导入或引用资源将内联为 base64 编码, 以避免额外的http请求, 设置为 0, 可以完全禁用此项,
assetsInlineLimit: 4096,
// 启动 / 禁用 CSS 代码拆分
cssCodeSplit: true,
// 构建后是否生成 soutrce map 文件
sourcemap: false,
// 自定义底层的 Rollup 打包配置
rollupOptions: {
input: {
admin: path.resolve(__dirname, 'src/index.html'),
page: path.resolve(__dirname, 'src/page/index.html'),
index: path.resolve(__dirname, 'src/index/index.html'),
},
output: {
chunkFileNames: 'static/js/[name]-[hash].js',
entryFileNames: 'static/js/[name]-[hash].js',
assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
}
},
// @rollup/plugin-commonjs 插件的选项
commonjsOptions: {},
// 构建的库
// lib: { entry: string, name?: string, formats?: ('es' | 'cjs' | 'umd' | 'iife')[], fileName?: string },
// 当设置为 true, 构建后将会生成 manifest.json 文件
manifest: false,
// 设置为 false 可以禁用最小化混淆
// 或是用来指定是应用哪种混淆器
// boolean | 'terser' | 'esbuild'
minify: 'terser',
// 传递给 Terser 的更多 minify 选项
terserOptions: {},
// 设置为false 来禁用将构建好的文件写入磁盘
write: true,
// 默认情况下 若 outDir 在 root 目录下, 则 Vite 会在构建时清空该目录。
emptyOutDir: true,
// 启用 / 禁用 brotli 压缩大小报告
brotliSize: false,
// chunk 大小警告的限制
chunkSizeWarningLimit: 500
}
})