Globally registered components
If multiple pages need to use this component, you can register this component as a global component.
Global registration: Use Vue.component('component name', component) to configure global components, for example:
// 第二步:全局注册组件
Vue.component('FrameHead',FrameHead);
Suppose there are two pages, using a component at the same time:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Vue2全局注册组件</title>
<script src="./js/vue.js"></script>
</head>
<body>
<!-- 页面一 -->
<div id="APP1">
<p>页面一</p>
<my-code></my-code>
</div>
<hr/>
<!-- 页面二 -->
<div id="APP2">
<p>页面二</p>
<my-code></my-code>
</div>
<script>
// 第一步:创建 MyCode 组件
const MyCode = {
template: `
<div>
<p>{
{title}}</p>
</div>
`,
data() {
return {
title: "你好呀!"
}
}
}
// 第二步:全局注册组件
Vue.component('MyCode',MyCode);
// 页面一的 Vue 实例
const vm1 = new Vue({
el: "#APP1"
});
// 页面二的 Vue 实例
const vm2 = new Vue({
el: "#APP2"
});
</script>
</body>
</html>
Note : After the component is registered globally, there is no need to define it in new Vue(), and all Vue instances can use this component.
Component nested use
Create subcomponents:
// 第一步:创建 crumbs 组件【子组件】
const crumbs = Vue.extend({
template:`
<div>
<span v-for="(item,index) in list" :key="index"> {
{item}} </span>
</div>
`,
data(){
return {
list: ["首页","用户管理","商品管理","轮播图管理"]
}
}
})
Create parent component:
// 第一步:创建 frameHead 组件【父组件】
const frameHead = Vue.extend({
template: `
<div>
<strong>{
{title}}</strong>
<span>{
{username}}</span>
<hr/>
<crumbs></crumbs>
</div>
`,
data() {
return {
title: "商城管理系统",
username: "张三"
}
},
// 注册子组件
components: {
crumbs
}
})
Note : There are also components configuration items in the component, and subcomponents can be registered in the component, and the subcomponents can be written into the current template for use.
Create a Vue instance:
const vm = new Vue({
el: "#APP",
components: {
frameHead
}
});
Note : There is no need to register subcomponents in the Vue instance
use components
<div id="APP">
<frame-head></frame-head>
</div>
Full code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>vue2 组件嵌套使用</title>
<script src="./js/vue.js"></script>
</head>
<body>
<div id="APP">
<frame-head></frame-head>
</div>
<script>
// 第一步:创建 crumbs 组件【子组件】
const crumbs = Vue.extend({
template: `
<div>
<span v-for="(item,index) in list" :key="index"> {
{item}} </span>
</div>
`,
data() {
return {
list: ["首页", "用户管理", "商品管理", "轮播图管理"]
}
}
})
// 第一步:创建 frameHead 组件【父组件】
const frameHead = Vue.extend({
template: `
<div>
<strong>{
{title}}</strong>
<span>{
{username}}</span>
<hr/>
<crumbs></crumbs>
</div>
`,
data() {
return {
title: "商城管理系统",
username: "张三"
}
},
// 注册子组件
components: {
crumbs
}
})
const vm = new Vue({
el: "#APP",
components: {
frameHead
}
});
</script>
</body>
</html>
Original author: Wu Xiaotang
Creation time: 2023.5.13