注册局部组件,这个组件只能在这个实例中使用
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script src="vue.js"></script>
<div id="app">
<name></name> //H5中没有name标签,是我们自定义的
</div>
<script>
var test = {
template: "<h1>测试内容</h1>" //标签里的内容
}
new Vue({
el: "#app",
components: {
"name": test //name是标签名,test用来获取自定义的标签里的内容
}
})
</script>
</body>
</html>
注册全局组件,所有实例都能使用
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script src="vue.js"></script>
<div id="app">
<name></name> //name是自定义的标签
</div>
<script>
Vue.component("name",{template:"<h1>测试内容</h1>"})
new Vue({
el:"#app"
})
</script>
</body>
</html>
Prpo传参,Prpo是子组件用来接受父组件传递过来的数据的一个自定义属性
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script src="vue.js"></script>
<div id="app">
<name message="测试传参"></name>
</div>
<script>
Vue.component("name",
{template:"<h1>{{message}}</h1>",
props:["message"] //这里不用props传参的话,template里的message就获取不到值
})
new Vue({
el:"#app"
})
</script>
</body>
</html>
使用Prop结合v-bind,可以实现动态传参。每当父组件的数据变化时,这个变化也会传给子组件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
</head>
<body>
<div id="app">
<div>
<input v-model="parentMsg">
<br>
<child v-bind:message="parentMsg"></child>
</div>
</div>
<script>
Vue.component('child', {
props: ['message'],
template: '<span>{{ message }}</span>'
})
new Vue({
el: '#app',
data: {
parentMsg: '父组件内容'
}
})
</script>
</body>
</html>