<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>组件的创建注册和使用</title>
<script src="../js/vue.js"></script>
</head>
<body>
<div id="app">
<h1>{{msg}}</h1>
<!-- 3.使用组件 -->
<userlist></userlist>
<userlist></userlist>
<userlogin></userlogin>
<userlogin></userlogin>
</div>
<script>
// 1.创建组件
const userListComponent = Vue.extend({
template : `
<ul>
<li v-for="(user,index) of users" :key="user.id">
{{index}},{{user.name}}
</li>
</ul>
`,
data(){
return {
users : [
{id:'001', name:'jack'},
{id:'002', name:'lucy'},
{id:'003', name:'james'}
]
}
}
})
// 1.创建组件
const userLoginComponent = Vue.extend({
template : `
<div>
<h3>用户登录</h3>
<form @submit.prevent="login">
账号:<input type="text" v-model="username"><br><br>
密码:<input type="password" v-model="password"><br><br>
<button>登录</button>
</form>
</div>
`,
data(){
return {
username : 'admin',
password : '123'
}
},
methods : {
login(){
alert(this.username + "," + this.password)
}
}
})
const vm = new Vue({
el : '#app',
data : {
msg : '组件的创建注册和使用'
},
// 2.注册组件(局部注册)
components : {
// userlist 就是组件的名字
userlist : userListComponent,
userlogin : userLoginComponent
}
})
</script>
</body>
</html>
(1) 创建组件
1 const userComponent = Vue.extend({这个配置项和创建 Vue 实例的配置项几乎是一样的,只是略有差异})
2 需要注意的是:
1) el 不能用。组件具有通用性,不特定为某个容器服务,它为所有容器服务。
2) data 必须使用函数形式:return {}
3) 使用 template 配置项配置页面结构:HTML。
(2) 注册组件
1 局部注册
1) 使用 components 配置项:components : {user : userComponent},user 就是组件名。
2 全局注册
1) Vue.component(‘user’, userComponent)
(3) 使用组件
1 直接在页面需要使用组件的位置:
2 也可以这样使用:
(4) 创建组件对象也有简写形式:Vue.extend() 可以省略。直接写:{}
(5) 组件的命名细节:
1 全部小写
2 首字母大写,后面全部小写
3 kebab-case 串式命名法
4 CamelCase 驼峰式命名法(这种方式需要在脚手架环境中使用)
5 不要使用 HTML 内置的标签作为组件名称。
6 可以使用 name 配置项来指定 Vue 开发者工具中显示的组件名。