首页 > 应用开发 > XML/XSL > Vue最佳实践和实用技巧
props: {
size: {
// 自定义验证函数
validator: (val) => {
return ["small", "medium", "large"].includes(val);
},
}}复制代码<!-- 此组件为二次封装的中间组件 --><template>
<MyComponent v-bind="$attrs"/></template><script>
export default {
// $attrs 中的所有属性不自动继承到组件的根元素上
inheritAttrs: false,
}</script>复制代码const attrs = useAttrs();const filteredAttrs = computed(() => {
return { ...attrs, style: undefined };});复制代码<MyComponent v-bind="$attrs" v->
<About> <template #about> <slot name="about" /> </template></About>复制代码
<template #[slotName] v-for="(slot, slotName) in $slots" > <slot :name="slotName"/></template>复制代码
<template #[slotName]="slotProps" v-for="(slot, slotName) in $slots" > <slot :name="slotName" v-bind="slotProps"/></template><!-- Vue2则需要将v-for里面循环的$slots改成$scopedSlots -->复制代码
const path = require("path");// 参数一:说明需要检索的目录,参数二:是否检索子目录,参数三::指定匹配文件名的正则表达式const files = require.context("./components", false, /\.vue$/);const modules = {};files.keys().forEach((key) => {
const name = path.basename(key, ".vue");
modules[name] = files(key).default || files(key);});复制代码const modules = import.meta.glob('./src/*.js');// vite 转译上面后生成的代码const modules = {
'./src/foo.js': () => import('./src/foo.js'),
'./src/bar.js': () => import('./src/bar.js')}复制代码const $slots = {
"default": [{...}],
"slotA": [{...}],
"slotB": [{...}]}复制代码<template> <div> <div v-if="$slots.default"> <slot /> </div> <div v-if="$slots.slotA"> <slot name="slotA"/> </div> </div></template>复制代码
window.addEventListener('mousedown', e => {
// 获取被点击的元素
const clickedEl = e.target;
// `targetEl` 为检测的元素
if (targetEl.contains(clickedEl)) {
// 在"targetEl"内部点击
} else {
// 在"targetEl"之外点击
}});复制代码<transition> <keep-alive> <!-- :is值必须是全局或者局部注册过的组件 --> <component :is="currentTab"></component> </keep-alive></transition>复制代码
<div v-if="item.children">
{{ tree.label }}
<!-- 递归调用自身 -->
<tree v-for="(item, index) in tree.children" :tree="item" :key="index"></tree></div><script>
export default {
// 定义name,以使组件内部递归调用
name: 'tree',
// 接收外部传入的值
props: {
tree: {
type:Array,
default: () => []
}
}
}</script>复制代码mounted(){
this.$nextTick(() => {
this.$refs.inputs.focus(); //通过 $refs 获取dom 并绑定 focus 方法
})}复制代码<div :class=" $route.name === 'Home' || $route.name === 'Gallery' || $route.name === 'Profile' ? 'classOnlyOnThesePages' : '' " ></div>复制代码
<div :class="{
classOnlyOnThesePages: ['Home', 'Gallery', 'Profile'].includes(
$route.name
),
}"
></div>复制代码class Utils {
// 复制一段文字到剪切板
copyToClipboard(text) {
let copyText = document.createElement("input");
document.body.appendChild(copyText);
copyText.value = text;
copyText.select();
document.execCommand("copy");
document.body.removeChild(copyText);
}}export default new Utils();复制代码import Utils from "./utils/utils.js";// 设置全局方法Vue.prototype.$utils = Utils;复制代码
import Utils from "./utils/utils.js"; const app = createApp(App);// 设置全局方法app.config.globalProperties.$utils = Utils; app.mount("#app");复制代码接下来任何地方都能愉快的访问啦this.$utils.copyToClipboard(text);// Vue3 setupconst { proxy } = getCurrentInstance();proxy.$utils.copyToClipboard(text);复制代码<template>
<div id="app">
<router-view v-if="isActive" />
</div></template><script>export default {
name: "App",
// provider给下层组件重刷的方法
provide() {
return {
reload: this.reload,
};
},
data: {
isActive: true,
},
method: {
reload() {
this.isActive = false;
this.$nextTick(() => {
this.isActive = true;
});
},
},};</script>复制代码<script>export default {
inject: ["reload"],
methods: {
refresh() {
this.reload();
},
},};</script>复制代码<template>
<div v-if="isShow"></div></template><script>export default {
data() {
return {
isShow: true,
};
},
method: {
refresh() {
this.isShow = false;
this.$nextTick(() => {
this.isShow = true;
});
},
},};</script>复制代码<template>
<div :key="keyValue"></div></template><script>export default {
data() {
return {
keyValue: 0,
};
},
method: {
refresh() {
this.keyValue++;
},
},};</script>复制代码// Vue 3const app = createApp(App);app.config.errorHandler = (err) => {
console.error(err);};// Vue 2Vue.config.errorHandler = (err) => {
console.error(err);};复制代码<template>
<div class="card">
<h3>
{{ title }}
</h3>
<h4 v-if="isShow" class="card-desc">
{{ description }}
</h4>
<div v-if="isShow">
<slot />
</div>
<Home v-if="isShow" />
</div></template>复制代码<template>
<div class="card">
<h3>
{{ title }}
</h3>
<template v-if="isShow">
<h4 class="card-desc">
{{ description }}
</h4>
<div>
<slot />
</div>
<Home />
</template>
</div></template>复制代码<div
v-for="{ id, user } in [
{ id: 1, user: 'yun' },
{ id: 2, user: 'mu' },
]"
:key="id"
>
{{ user }}</div>复制代码<style>
/* 全局有效 */
.content p {
font-size: 12px;
}</style>
<style scoped>
/* 只在该组件内有效 */
.content {
background: green;
}</style>复制代码<style scoped>:deep(.ant-card-head-title){
background: green;
}</style>复制代码[data-v-e44d851a] .ant-card-head-title {
background: green;}复制代码<Card :type="Mytype" :color="Mycolor">复制代码
import Card from './Card.vue';export default {
components: { Card },
props: {
Mytype: {
type: String,
required: true,
},
Mycolor: {
type: String,
default: "green",
}
},};复制代码import Card from './Card.vue';const cardProps = {};Object.entries(Card.props).forEach(([key, value]) => {
cardProps[`My${key}`] = value;});export default {
components: { Card },
props: {
...cardProps
},};
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70021881/viewspace-2917235/ ,如需转载,请注明出处,否则将追究法律责任。