html5 使用vue 自定义组件
环境:html5 中使用发vue
vue版本:vue3
目标:自定义一个组件components.css ,使之引入就成使用
1创建组件js components.js
// 定义按钮组件
const Button = {
template: `
<button class="custom-btn" @click="add">
<slot name="title">{{text}}</slot>
{{val}}
</button>
`,
props: {
text: {
type: String,
default: '点击累计:'
}
},
data() {
return {
val:0,
}
},
methods: {
add() {
this.val++;
}
}
};
// 动态加载 CSS(可选)
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = 'components.css';
document.head.appendChild(link);2创建组件css components.css
/* components.css */
.custom-btn {
padding: 8px 16px;
background-color: #409eff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.custom-input {
padding: 8px;
border: 1px solid #dcdfe6;
border-radius: 4px;
width: 200px;
}3. html中使用
<!DOCTYPE html>
<html>
<head>
<title>类似 Element UI 的组件引入</title>
<!-- 引入 Vue3 -->
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<!-- 引入组件库 JS 和 CSS -->
<script src="components.js"></script>
</head>
<body>
<div id="app">
<custom-button><template #title>点击累加数字:</template></custom-button>
</div>
<script>
const App = {
data() {
},
methods:{
},
mounted(){
},
}
const app = Vue.createApp(App);
//挂载到vue
app.component('custom-button', Button);
app.mount("#app");
</script>
</body>
</html>理解:
app.component 负责把组件挂载的vue中
components.js 其实就是一个vue 组件的所有内容,通过js 赋值给一个常量
另一种简单组件的写法
<template id="my-component">
<div>这是一个全局组件(Vue3)</div>
</template>
<div id="app">
<my-component></my-component>
</app>
<script>
// 全局注册组件
const app = Vue.createApp({});
app.component('my-component', {
template: '#my-component'
});
app.mount('#app'); // 挂载到 DOM
</script>