我们在开发过程中,会复用许多的代码,我们不会写许多重复的代码,这样也会使我们的代码变得很臃肿,我们在c语言的学习过程中,使用到了函数来封装我们的函数来实现代码的复用,我们在vue中,可以使用组件来封装我们的代码。组件可以使我们很轻易地对我们的代码进行修改,任何我们所看到的页面都可以分解成组件。如下:
官方文档的例子,我们将一个页面分解为一颗树。
一个模板对象
其中,tagName为组件名,options为组件配置项。
例子中,'myButton’为组件名,temp为组件配置项。
tagName为我们自定义的组件名。
示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src = "../../js/vue.js"></script>
</head>
<body>
<div id = "app">
<!--使用组件-->
<my-button></my-button>
<my-button></my-button>
<my-button></my-button>
</div>
<script type = "text/javascript">
//创建组件构造器
const temp = Vue.extend({
template:
`<h1>
Good Morning
</h1>`
})
//注册组件
Vue.component('myButton',temp)
const app = new Vue({
el:"#app",
data:{
}
})
</script>
</body>
</html>
注意,不是vue实例不能使用任何的vue实例。
示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src = "../../js/vue.js"></script>
</head>
<body>
<div id = "app">
<my-button></my-button>
<my-button></my-button>
<my-button2></my-button2>
</div>
<div id = "app1">
<my-button></my-button>
<!--在这里不能用 <my-button2></my-button2>-->
</div>
<script type = "text/javascript">
const temp = Vue.extend({
template:`
<h2>Welcome to Vue</h2>
`
})
//全局组件
Vue.component('myButton',temp);
const app = new Vue({
el:"#app",
data:{
},
//局部组件
components:{
myButton2:temp
}
})
const app1 = new Vue({
el:"#app1",
})
</script>
</body>
</html>
如下面的例子,使用组件中的components属性,就可以在子组件中使用父组件。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src = "../../js/vue.js"></script>
</head>
<body>
<div id = "app">
<my-button></my-button>
</div>
<script type = "text/javascript">
const tempFather = Vue.extend({
template:
`<h1>
Good Morning
</h1>`
})
const tempSon = Vue.extend({
template:
`<div>
<h1>Good Night</h1>
<temp></temp>
</div>
`,
components:{
temp:tempFather
}
})
const app = new Vue({
el:"#app",
data:{
},
components:{
myButton:tempSon
}
})
</script>
</body>
</html>
我们以第一个实例为例子:
没使用语法糖前
使用语法糖后
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src = "../../js/vue.js"></script>
</head>
<body>
<div id = "app">
<!--使用组件-->
<my-button></my-button>
<my-button></my-button>
<my-button></my-button>
</div>
<script type = "text/javascript">
//创建组件构造器
//注册组件
Vue.component('myButton',{
template:
`<h1>
Good Morning
</h1>`
})
const app = new Vue({
el:"#app",
data:{
}
})
</script>
</body>
</html>
Keepalived 双机主备原理 1. Nginx 的高可用(High Availablity) 有两台Nginx形成...
V$PWFILE_USERS 列出的是password文件里已授予sysdba、sysoper权限的用户,如果...
我就废话不多说了,大家还是直接看代码吧~ template!--此div的高度取屏幕可视区...
一:概念 队列是一个”先进先出“的线性表,牛X的名字就是“First in First Out(...
3月14日消息 微软近日发布了 Edge 89 正式版浏览器,带来了垂直标签页等新功能,...
**解决的问题:** 使用$attrs和$listeners实现祖孙组件之间的数据传递,也就是多...
components/Button.vue template div button :disabled="$attrs.disabled"点击/b...
功能性是否可以装一半水、装满水是否可以正常喝水拧紧盖子摇晃是否漏水 兼容性是...
在JSP中,获取客户端IP的方法为:request.getRemoteAddr()。这种方法在大部分情...
目录 3.有两个关系SA,B,C,D和TC,D,E,F,写出与下列查询等价的SQL表达式 4.用SQL语...