vue3.x代码片段
pinia状态管理使用示例
【main.js】
import './assets/main.css'
import {createApp} from 'vue'
import {createPinia} from 'pinia'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(createPinia())
app.use(router)
app.mount('#app')
【src/stores/counter.js】
import {ref, computed} from 'vue'
import {defineStore} from 'pinia'
/**
* 计数器状态
*
* @author J
* @date 2023/6/9 23:38
*/
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
const doubleCount = computed(() => count.value * 2)
function increment() {
count.value++
}
return {count, doubleCount, increment}
})
/**
* 用户登录状态
*
* @author J
* @date 2023/6/9 23:38
*/
export const userLoginStore = defineStore("userLoginStatus", () => {
const loginStatus = ref(false);
return {loginStatus};
})
使用
<script setup>
import {useCounterStore, userLoginStore} from './stores/counter'
const countStatus = useCounterStore();
const userLoginStatus = userLoginStore();
onclick = () => {
countStatus.increment()
}
</script>
<template>
<div>
<h1>{{ countStatus.count }}</h1>
<h1>{{ userLoginStatus.loginStatus }}</h1>
</div>
</template>
全局变量使用示例一
import './assets/main.css'
import {createApp} from 'vue'
import {createPinia} from 'pinia'
import App from './App.vue'
import router from './router'
const app = createApp(App)
// 安装插件,会自动回调插件的init方法
app.use(createPinia())
app.use(router)
// 关键:提供出去一个全局变量
app.provide("global", "挂载了一个全局变量");
// 最后一步在挂载到根容器上
app.mount('#app')
使用
<script setup>
import {inject} from "vue";
// 注入这个全局变量
const g = inject('global');
// 使用全局变量
console.log("===========> " + g + " <===========")
</script>
<template>
<div>
<h1>{{ g }}</h1>
<h1>{{ g }}</h1>
</div>
</template>
全局变量使用示例二
Vue3组合式API之getCurrentInstance详解:https://www.jb51.net/article/263720.htm
import './assets/main.css'
import {createApp} from 'vue'
import {createPinia} from 'pinia'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(createPinia())
app.use(router)
app.config.globalProperties.$myg = "我是全局变量";
// 最后一步在挂载到根容器上
app.mount('#app')
使用
<script setup>
import {getCurrentInstance} from "vue";
var currentInstance = getCurrentInstance();
console.log(currentInstance.proxy.$myg);
</script>
<template>
<div><h1></h1></div>
</template>
<style scoped></style>
ref()方法使用示例
(关键)
在一个子组件中产生一个响应式的变量,这个变量就被vue代理变成响应式的- 用于操作虚拟DOM,将产生出来的变量与虚拟DOM绑定在一起,例如
<script setup>
import {inject, onMounted, ref} from "vue";
// 通过main变量操作div元素
const main = ref();
// 通过canvas变量操作canvas元素
const canvas = ref();
</script>
<template>
<div>
<div ref="main" style="width: 100%; height: 400px"></div>
<canvas ref="canvas"></canvas>
</div>
</template>
集成echarts数据分析图表
官网:https://echarts.apache.org/examples/zh/index.html
<script setup>
import * as echarts from "echarts";
import {onMounted, ref} from "vue";
const main = ref();
const canvas = ref();
onMounted(() => {
// 关键点,等虚拟DOM准备就绪,才能开始渲染
init();
})
function init() {
// 初始化echarts对象
const myChart = echarts.init(main.value);
const builderJson = {
all: 10887,
charts: {
map: 3237,
lines: 2164,
bar: 7561,
line: 7778,
pie: 7355,
scatter: 2405,
candlestick: 1842,
radar: 2090,
heatmap: 1762,
treemap: 1593,
graph: 2060,
boxplot: 1537,
parallel: 1908,
gauge: 2107,
funnel: 1692,
sankey: 1568
},
components: {
geo: 2788,
title: 9575,
legend: 9400,
tooltip: 9466,
grid: 9266,
markPoint: 3419,
markLine: 2984,
timeline: 2739,
dataZoom: 2744,
visualMap: 2466,
toolbox: 3034,
polar: 1945
},
ie: 9743
};
const downloadJson = {
'echarts.min.js': 17365,
'echarts.simple.min.js': 4079,
'echarts.common.min.js': 6929,
'echarts.js': 14890
};
const themeJson = {
'dark.js': 1594,
'infographic.js': 925,
'shine.js': 1608,
'roma.js': 721,
'macarons.js': 2179,
'vintage.js': 1982
};
const waterMarkText = 'ECHARTS';
const ctx = canvas.value.getContext('2d');
canvas.value.width = canvas.value.height = 100;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.globalAlpha = 1;
ctx.font = '20px Microsoft Yahei';
ctx.translate(50, 50);
ctx.rotate(-Math.PI / 4);
ctx.fillText(waterMarkText, 0, 0);
const option = {
backgroundColor: {
type: 'pattern',
image: canvas,
repeat: 'repeat'
},
tooltip: {},
title: [
{
text: '在线构建',
subtext: '总计 ' + builderJson.all,
left: '25%',
textAlign: 'center'
},
{
text: '各版本下载',
subtext:
'总计 ' +
Object.keys(downloadJson).reduce(function (all, key) {
return all + downloadJson[key];
}, 0),
left: '75%',
textAlign: 'center'
},
{
text: '主题下载',
subtext:
'总计 ' +
Object.keys(themeJson).reduce(function (all, key) {
return all + themeJson[key];
}, 0),
left: '75%',
top: '50%',
textAlign: 'center'
}
],
grid: [
{
top: 50,
width: '50%',
bottom: '45%',
left: 10,
containLabel: true
},
{
top: '55%',
width: '50%',
bottom: 0,
left: 10,
containLabel: true
}
],
xAxis: [
{
type: 'value',
max: builderJson.all,
splitLine: {
show: false
}
},
{
type: 'value',
max: builderJson.all,
gridIndex: 1,
splitLine: {
show: false
}
}
],
yAxis: [
{
type: 'category',
data: Object.keys(builderJson.charts),
axisLabel: {
interval: 0,
rotate: 30
},
splitLine: {
show: false
}
},
{
gridIndex: 1,
type: 'category',
data: Object.keys(builderJson.components),
axisLabel: {
interval: 0,
rotate: 30
},
splitLine: {
show: false
}
}
],
series: [
{
type: 'bar',
stack: 'chart',
z: 3,
label: {
position: 'right',
show: true
},
data: Object.keys(builderJson.charts).map(function (key) {
return builderJson.charts[key];
})
},
{
type: 'bar',
stack: 'chart',
silent: true,
itemStyle: {
color: '#eee'
},
data: Object.keys(builderJson.charts).map(function (key) {
return builderJson.all - builderJson.charts[key];
})
},
{
type: 'bar',
stack: 'component',
xAxisIndex: 1,
yAxisIndex: 1,
z: 3,
label: {
position: 'right',
show: true
},
data: Object.keys(builderJson.components).map(function (key) {
return builderJson.components[key];
})
},
{
type: 'bar',
stack: 'component',
silent: true,
xAxisIndex: 1,
yAxisIndex: 1,
itemStyle: {
color: '#eee'
},
data: Object.keys(builderJson.components).map(function (key) {
return builderJson.all - builderJson.components[key];
})
},
{
type: 'pie',
radius: [0, '30%'],
center: ['75%', '25%'],
data: Object.keys(downloadJson).map(function (key) {
return {
name: key.replace('.js', ''),
value: downloadJson[key]
};
})
},
{
type: 'pie',
radius: [0, '30%'],
center: ['75%', '75%'],
data: Object.keys(themeJson).map(function (key) {
return {
name: key.replace('.js', ''),
value: themeJson[key]
};
})
}
]
};
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);
}
</script>
<template>
<div>
<div ref="main" style="width: 100%; height: 400px"></div>
<canvas ref="canvas"></canvas>
</div>
</template>
<style scoped>
</style>
nextTick()函数
<script setup>
import {nextTick} from "vue";
console.log("===========> " + "渲染开始1" + " <===========")
nextTick(() => {
console.log("===========> " + "nextTick回调执行时刻3" + " <===========")
})
console.log("===========> " + "渲染结束2" + " <===========")
</script>
<template>
<div>
</div>
</template>
<style scoped>
</style>
集成chartjs数据分析图表
官网:https://www.chartjs.org/docs/latest/
安装:npm i vue-chartjs chart.js
- 组合式API写法
<script setup>
import {Chart as ChartJS, Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale} from 'chart.js'
import {Bar} from 'vue-chartjs'
import {ref} from "vue";
ChartJS.register(CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend)
const data = ref();
data.value = {
labels: ['January', 'February', 'March'],
datasets: [{label: '我是标题', data: [40, 20, 12]}]
}
const options = ref();
options.value = {responsive: true}
</script>
<template>
<Bar :data="data" :options="options"/>
</template>
<style scoped></style>
- 选项式API写法
<script>
import {Chart as ChartJS, Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale} from 'chart.js'
import {Bar} from 'vue-chartjs'
ChartJS.register(CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend)
export default {
name: 'App',
components: {
Bar
},
data() {
return {
data: {
labels: ['January', 'February', 'March'],
datasets: [
{label: '# of Votes', data: [40, 20, 12]}
]
},
options: {responsive: true}
}
}
}
</script>
<template>
<Bar :data="data" :options="options"/>
</template>
<style scoped></style>
集成socket.io
Vue 使用 Vue-socket.io 实现即时聊天应用(Vue3连接原理分析):https://blog.csdn.net/weixin_47746452/article/details/126827806
Socket接口测试工具 (socket.io.js):https://blog.csdn.net/xutongbao/article/details/82253042
对应后台socket.io实现:https://github.com/jia-1024/java-workspace/tree/main/demo/SpinrgBoot-socketio
WebSocket和Socket.io之间的区别(译):https://zhuanlan.zhihu.com/p/346650330
vue-socket.io使用简介:https://www.jsdelivr.com/package/npm/vue-socket.io
安装:npm i vue-socket.io
使用APP.vue
<script setup>
import VueSocketIO from "vue-socket.io";
const socket = new VueSocketIO({
// debug调试,生产建议关闭
debug: true,
connection: "ws://127.0.0.1:8888?userId=2",
});
</script>
<template>
<div><h1></h1></div>
</template>
<style scoped></style>