Vue 组件与复用
(1)全局注册
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>Vue</title>
</head>
<body>
<div id="app">
<my-component>
</my-component>
</div>
<script src="https://cdn.bootcss.com/vue/2.5.9/vue.min.js"></script>
<script type="text/javascript">
//示例前注册
Vue.component('my-component', {
//DOM结构必须被元素包含
template: '<div>组件内容</div>'
})
new Vue({
el: "#app"
})
</script>
</body>
</html>
(2)局部注册
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>Vue</title>
</head>
<body>
<div id="app">
<my-component>
</my-component>
</div>
<script src="https://cdn.bootcss.com/vue/2.5.9/vue.min.js"></script>
<script type="text/javascript">
var Child = {
template: '<div>组件内容</div>'
}
new Vue({
el: "#app",
components: {
'my-component': Child
}
})
</script>
</body>
</html>
(3)is挂载组件
table、ul、ol、select这些标签会限制其内的元素,这时可以使用is来挂载组件
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>Vue</title>
</head>
<body>
<div id="app">
<table>
<tbody is='my-component'>
</tbody>
</table>
</div>
<script src="https://cdn.bootcss.com/vue/2.5.9/vue.min.js"></script>
<script type="text/javascript">
//示例前注册
Vue.component('my-component', {
//DOM结构必须被元素包含
template: '<div>组件内容</div>'
})
new Vue({
el: "#app"
})
</script>
</body>
</html>
(4)组件也可以有data,method,computed等属性。但是data是函数,数据需要return出去。
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>Vue</title>
</head>
<body>
<div id="app">
<my-component></my-component>
</div>
<script src="https://cdn.bootcss.com/vue/2.5.9/vue.min.js"></script>
<script type="text/javascript">
//示例前注册
Vue.component('my-component', {
//DOM结构必须被元素包含
template: '<div>{{message}}</div>',
data: function() {
return {
message: '组件内容'
}
}
})
new Vue({
el: "#app"
})
</script>
</body>
</html>
(5)解决多个组件之间数据共享问题
给组件返回一个新的data对象
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>Vue</title>
</head>
<body>
<div id="app">
<my-component></my-component>
<my-component></my-component>
<my-component></my-component>
</div>
<script src="https://cdn.bootcss.com/vue/2.5.9/vue.min.js"></script>
<script type="text/javascript">
//示例前注册
Vue.component('my-component', {
//DOM结构必须被元素包含
template: '<button @click="counter++">{{counter}}</button>',
data: function() {
return {
counter: 0
}
}
})
new Vue({
el: "#app"
})
</script>
</body>
</html>
(6)props传递数据、events触发事件和slot内容分发构成Vue组件的3个API来源。
作者:孟繁贵 Email:meng010387@126.com 期待共同进步!