①全局组件
components/index.js文件中:
Vue.component('mytag', {
template: `<div>放HTML代码</div>`, // template 模板 也就是html
data() {return {}},
methods: {},
watch: {},
....
})
views/index.html文件中:
使用组件:<mytag></mytag> //mytag为组件名
②父子组件
<div id="app">
<mytag1></mytag1>
</div>
<script>
Vue.component('mytag1', { //(<logout />)是子组件
template: `<p @click="say"> {{name}} (<logout />) {{age}} </p>`,
data() {
return {
name: "刘德华",
age: 100
}
},
methods: {
say() {
alert('hello')
}
},
// 通过components来声明子组件
components: {
logout: {
template: `<a href="">退出</a>`
}
}
})
③动态组件
<!DOCTYPE html>
<html lang="en">
<head>
<title>动态组件</title>
<meta charset="UTF-8" />
</head>
<body>
<div id="app">
<ul>
<li @click="active = 'index'">首页</li>
<li @click="active = 'jiadian'">家电</li>
<li @click="active = 'baojian'">保健</li>
<li @click="active = 'meirong'">美容</li>
</ul>
<component v-bind:is="active"></component>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
// 造组件
Vue.component('index', {
template: `<fieldset><div>首页</div></fieldset>`
})
Vue.component('jiadian', {
template: `<fieldset><div>家电</div></fieldset>`
})
Vue.component('baojian', {
template: `<fieldset><div>保健</div></fieldset>`
})
Vue.component('meirong', {
template: `<fieldset><div>美容</div></fieldset>`
})
const vm = new Vue({
el: '#app',
data: {
active: 'jiadian'
}
})
</script>
</body>
</html>