Vue组件基础

时间:2019-03-21
本文章向大家介绍Vue组件基础,主要包括Vue组件基础使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

定义一个组件:

 1 <template>
 2   <header>
 3       <h1>{{title}}</h1>
 4   </header>
 5 </template>
 6 
 7 <script>
 8 export default {
 9   name: 'app-header',
10   data () {
11     return {
12       title: 'Welcome to Your Vue.js App'
13     }
14   }
15 }
16 </script>
17 
18 <!-- Add "scoped" attribute to limit CSS to this component only -->
19 <style scoped>
20 header{
21     background: lightgreen;
22     padding: 10px;
23 }
24 h1{
25     color: purple;
26     text-align: center;
27 }
28 </style>
View Code

 在另一个组件中使用该组件,首先引入该组件,然后注册该组件(启发:通过组件的嵌套来实现页面的拼装)

 1 /*app.vue是根组件*/
 2 
 3 /*模板,HTML结构*/
 4 <template>
 5   <div id="home">
 6     
 7     <app-header></app-header>
 8     <h2> hello world!{{title}} </h2>
 9     <users></users>
10     <br>
11     <app-footer></app-footer>
12   </div>
13 </template>
14 
15 /*行为,处理逻辑*/
16 <script>
17 //局部注册组件
18 import Users from './Users'
19 import Header from './Header'
20 import Footer from './Footer'
21 export default {
22   name: 'home',
23   data(){
24     return{
25       title:"这是我的第一Vue脚手架工具!"
26     }
27   },
28   components:{
29     "users":Users,
30     "app-header":Header,
31     "app-footer":Footer
32   }
33 }
34 </script>
35 
36 /*样式:解决样式*/
37 <style scoped>
38 h2{
39   color: green;
40 }
41 </style>
View Code

 一个组件的 data 选项必须是一个函数,因此每个实例可以维护一份被返回对象的独立的拷贝:

1 data: function () {
2   return {
3     count: 0
4   }
5 }
View Code

通常一个应用会以一棵嵌套的组件树的形式来组织:

例如,你可能会有页头、侧边栏、内容区等组件,每个组件又包含了其它的像导航链接、博文之类的组件。

上面代码中组件注册的方式是局部注册,只能在引入该组件的Vue实例中使用。

也可以通过全局注册的方式注册组件:

1 // 定义一个名为 button-counter 的新组件
2 Vue.component('button-counter', {
3   data: function () {
4     return {
5       count: 0
6     }
7   },
8   template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>'
9 })
View Code

父组件向子组件传值

Vue.component('blog-post', {
  props: ['title'],
  template: '<h3>{{ title }}</h3>'
})

<!--
一个组件默认可以拥有任意数量的 prop,任何值都可以传递给任何 prop。在上述模板中,你会发现我们能够在组件实例中访问这个值,就像访问 data 中的值一样。
-->
new Vue({
  el: '#blog-post-demo',
  data: {
    posts: [
      { id: 1, title: 'My journey with Vue' },
      { id: 2, title: 'Blogging with Vue' },
      { id: 3, title: 'Why Vue is so fun' }
    ]
  }
})


<blog-post
  v-for="post in posts"
  v-bind:key="post.id"
  v-bind:title="post.title"
></blog-post>

 tips:every component must have a single root element (每个组件必须只有一个根元素)


 子组件向父组件传值:

Vue.component('welcome-button', {
  template: `
    <button v-on:click="$emit('welcome')">
      Click me to be welcomed
    </button>
  `
})
<div id="emit-example-simple">
  <welcome-button v-on:welcome="sayHi"></welcome-button>
</div>
new Vue({
  el: '#emit-example-simple',
  methods: {
    sayHi: function () {
      alert('Hi!')
    }
  }
})
View Code