解析Vue.js中的组件(3)
你能猜到上面发生了什么吗?
有两个组件,并且这两个组件共享相同的数据源,因为数据不作为对象返回。 你怎么证明我是对的? 当从浏览器查看上述页面时,你将看到一个组件的更改会导致另一个组件的数据发生更改。那么它应该是怎样的呢?
像这样:
<!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
开始你的新的Vue.js项目:
vue init webpack vue-component-app
导航到你的应用程序,安装依赖关系,并使用下面的命令运行你的开发服务器。
cd vue-component-app npm install npm run dev
首先,你将重命名HelloWorld组件,这个组件是你将应用程序初始化为Hello.vue时创建的组件。然后你将注册这个组件作为一个全局组件在你的应用程序中使用。
所以你的Hello组件应该看起来像这样。
#src/components/Hello.vue
<template>
<div class="hello">
<p>Welcome to TutsPlus {{ name }}</p>
<hr>
<button @click="changeName">Change Display Name</button>
</div>
</template>
<script>
export default {
name: 'Hello',
data () {
return {
name: 'Henry'
}
},
methods: {
changeName () {
this.name = 'Mark'
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
font-weight: normal;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
内容版权声明:除非注明,否则皆为本站原创文章。
