除了根組件之外的全局組件和局部組件的data數(shù)據(jù)必須是函數(shù)
data(){
return {
}
}
根組件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vue</title>
<script type="text/javascript" src="vue.js"></script>
</head>
<body>
<div id="app">
{{msg}}
</div>
<script type="text/javascript">
//下面的new Vue就是根組件
var app = new Vue({
el: '#app',
data: {
msg: 'hello,world'
}
})
</script>
</body>
</html>
全局組件:
全局組件注冊方式:Vue.component(組件名,{方法})
全局組件必須寫在Vue實例創(chuàng)建之前走敌,才在該根元素下面生效递惋;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vue</title>
<script type="text/javascript" src="vue.js"></script>
</head>
<body>
<div id="app">
{{msg}}
<child-component/>
</div>
<script type="text/javascript">
//使用Vue.component()方法定義全局組件,參數(shù)一是組件名砸彬,參數(shù)二是組件模板和數(shù)據(jù)等
Vue.component('child-component',{
template: '<h1>hello,世界关斜!</h1>'
})
//下面的new Vue就是根組件
var app = new Vue({
el: '#app',
data: {
msg: 'hello,world'
}
})
</script>
</body>
</html>
局部組件||子組件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vue</title>
<script type="text/javascript" src="vue.js"></script>
</head>
<body>
<div id="app">
{{msg}}
<hdcms></hdcms>
</div>
<script type="text/javascript">
//下面的new Vue就是根組件
var app = new Vue({
el: '#app',
data: {
msg: 'hello,world666'
},
// 局部組件||子組件
components: {
hdcms: {
template: '<h3>我是子666組件</h3>'
}
}
})
</script>
</body>
</html>
組件的template模板可以拆出來
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vue</title>
<script type="text/javascript" src="vue.js"></script>
</head>
<body>
<div id="app">
{{msg}}
<hdcms></hdcms>
</div>
<!-- 這里把子組件的模板拆出來書寫 -->
<script type="text/x-template" id="news">
<div>
<h3>我是子組件的模板</h3>
</div>
</script>
<script type="text/javascript">
//下面的new Vue就是根組件
var app = new Vue({
el: '#app',
data: {
msg: 'hello,world666'
},
// 局部組件||子組件
components: {
hdcms: {
template: '#news'
}
}
})
</script>
</body>
</html>