解析Vue.js中的组件

2020-06-16 05:41:00易采站长站整理


<!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>

你能猜到上面发生了什么吗?

有两个组件,并且这两个组件共享相同的数据源,因为数据不作为对象返回。 你怎么证明我是对的? 当从浏览器查看上述页面时,你将看到一个组件的更改会导致另一个组件的数据发生更改。那么它应该是怎样的呢?

像这样:


<!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>

Vue.component('welcome-message', {
data: function() {
return {
name: 'Henry'
}
},
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>

这里的数据是作为一个对象返回的,一个组件的改变不会影响另一个组件。 该功能是针对单个组件执行的。 在构建应用程序时,不要忘记这一点,这很重要。

创建和使用组件

使用到目前为止学到的内容,让我们使用 vue -cli 从头开始一个新的Vue.js项目来实现它。 如果你的机器上没有安装 vue -cli ,你可以通过运行:


npm install -g vue-cli