让我们使用上面的内容创建一个组件。
Vue.component('welcome-message', {
data: function() {
return {
domain: 'Tutsplus'
}
},
template: '<p>Welcome to {{ domain }}</p>'
})
在上面,组件名称被称为welcome-message。 你的组件可以有你选择的任何名称。 然而重要的是,这个名字不会影响任何HTML标签,因为你不想重写它。
传递给构造函数的options对象包含数据和模板。 在创建组件时,你的数据应该是一个函数,如上所见。 被保存的数据应该作为一个对象返回。
在没有数据可以传递的情况下,传递如下的模板:
Vue.component('welcome-message', {
template: '<p>Welcome to Tutsplus</p>'
})
完成之后,可以通过使用传递给构造函数的名称将其当作常规HTML元素来在应用程序中使用组件。 它被这样调用:<welcome-message> </ welcome-message>。
要多次输出模板,可以根据需要多次调用组件,如下所示。
<!DOCTYPE html>
<html>
<head>
<title>VueJs Components</title>
</head>
<body>
<!-- Div where Vue instance will be mounted -->
<div id="app">
<welcome-message></welcome-message>
<welcome-message></welcome-message>
<welcome-message></welcome-message>
<welcome-message></welcome-message>
</div>
<!-- Vue.js is included in your page via CDN -->
<script src="https://unpkg.com/vue"></script>
<script>
Vue.component('welcome-message', {
data: function() {
return {
domain: 'Tutsplus'
}
},
template: '<p>Welcome to {{ domain }}</p>'
})
// A new Vue instance is created and mounted to your div element
new Vue({
el: '#app'
});
</script>
</body>
</html>
这样一来,欢迎消息将显示四次。
将数据存储在组件中
上面我提到数据必须是一个函数,它所包含的信息必须作为一个对象返回。 为什么这样?
当返回的数据不是对象时,使用该数据的组件共享相同的源:共享数据。 因此,一个组件的数据变化会影响另一个组件。 当数据作为对象返回时,这是不一样的。
看看这是如何实际工作是很重要的。 首先,让我们看看数据作为对象返回的情况。
<!DOCTYPE html>
<html>
<head>
<title>VueJs Components</title>
</head>
<body>
<!-- Div where Vue instance will be mounted -->
<div id="app">
<welcome-message></welcome-message>
<welcome-message></welcome-message>
</div>
<!-- Vue.js is included in your page via CDN -->
<script src="https://unpkg.com/vue"></script>
<script>
var data = { name: 'Henry' }
Vue.component('welcome-message', {
data: function() {
return data
},
template: '<p>Hello {{ name }}, welcome to TutsPlus (<button @click="changeName">Change Name</button>)</p>',
methods :{
changeName: function() {
this.name = 'Mark'
}
}
})
// A new Vue instance is created and mounted to your div element
new Vue({
el: '#app'
});
</script>
</body>
</html>
内容版权声明:除非注明,否则皆为本站原创文章。
